Amplify allows the creation of entities through generated code. I’d like to harness this to create several entities at once.
When a user creates an entity, say Event
,
const Event = a
.model({
id: a.id().required(),
title: a.string(),
eventOwnerId: a.id().required(),
eventOwner: a.belongsTo("EventOwner", "eventOwnerId"),
...
})
.authorization((allow) => [allow.owner()]);
where
const EventOwner = a
.model({
id: a.id().required(),
userId: a.id().required(), // should be associated with a user
eventId: a.id().required(),
events: a.hasMany("Event", "eventOwnerId"),
})
.authorization((allow) => [allow.owner()]);,
a given property on that event, say eventOwner
should be automatically populated through the following process.
- If an
EventOwner
is associated with the user who submitted thecreateEvent
mutation, the created event will automatically be associated via thatEventOwner
via itseventOwnerId
. - If an
EventOwner
is not associated with the user who submitted thecreateEvent
mutation, the created event will automatically generate aEventOwner
entity. And, thatEventOwner
should automatically be associated with the newly createdEvent
.
I believe this should be accomplished through a lambda function. So, I believe should have
- an
amplify/functions/pre-event-creation/resource.ts
with `import { defineFunction } from “@aws-amplify/backend”;
export const preEventCreation = defineFunction({name: "pre-event-creation",});`
- and an
amplify/functions/pre-event-creation/handler.ts
, which I suspect should look something like:
import { Amplify } from "aws-amplify";
import { generateClient } from "aws-amplify/data";
import type { PostConfirmationTriggerHandler } from "aws-lambda";
import { type Schema } from "../../data/schema";
import { preEventCreation } from "./resource";
import { env } from "$amplify/env/post-confirmation";
Amplify.configure(
{
API: {
GraphQL: {
endpoint: env.AMPLIFY_DATA_GRAPHQL_ENDPOINT,
region: env.AWS_REGION,
defaultAuthMode: "iam",
},
},
},
{
Auth: {
credentialsProvider: {
getCredentialsAndIdentityId: async () => ({
credentials: {
accessKeyId: env.AWS_ACCESS_KEY_ID,
secretAccessKey: env.AWS_SECRET_ACCESS_KEY,
sessionToken: env.AWS_SESSION_TOKEN,
},
}),
clearCredentialsAndIdentityId: () => {
/* noop */
},
},
},
}
);
const client = generateClient<Schema>({
authMode: "iam",
});
export const handler: PostConfirmationTriggerHandler = async (event) => {
await client.graphql({
query: preEventCreation,
variables: {
input: {
email: event.request.userAttributes.email,
profileOwner: `${event.request.userAttributes.sub}::${event.userName}`,
},
},
});
return event;
};
Specifically, I’d like to know what to add to the handler. Thanks in advance!
I’ve tried variations on the PostConfirmationTriggerHandler from the amplify docs, but haven’t made much headway.
user25441048 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.