SecretLumberjack
SecretLumberjack

Reputation: 11

AWS Amplify Gen 2: ctx.stash is empty in AppSync JS resolver when using custom handler

I am trying to write a custom batch mutation using Amplify Gen 2, but running it results in an error:

DynamoDB:DynamoDbException", message: "User: arn:aws:sts::{AWS_ACCOUNT_ID}:assumed-role/MyGroupRole-XXXXX-NONE/APPSYNC_ASSUME_ROLE is not authorized to perform: dynamodb:BatchWriteItem on resource: arn:aws:dynamodb:us-west-2:{AWS_ACCOUNT_ID}:table/Group-- because no identity-based policy allows the dynamodb:BatchWriteItem action (Service: DynamoDb, Status Code: 400, Request ID: {REQUEST_ID})

"Group--" seems to be the issue and it should be the full table name. According to the documentation, it should get awsAppsyncApiId and amplifyApiEnvironmentName from ctx.stash, but when I tried logging them, stash was an empty Object.

// mutation from amplify/data/resource.ts
  BatchUpdateGroupRanks: a.mutation().arguments({
    resumeID: a.string(),
    ids: a.string().array().required(),
    ranks: a.integer().array().required(),
  })
  .returns(a.ref('Group').array())
  .authorization(allow => [allow.authenticated()])
  .handler(
    a.handler.custom({
      dataSource: a.ref('Group'),
      entry: './BatchUpdateGroupRanksHandler.js',
    })
  ),

// BatchUpdateGroupRanksHandler.js
export function request(ctx) {
    const tableName = `Group-${ctx.stash.awsAppsyncApiId}-${ctx.stash.amplifyApiEnvironmentName}`;
    const now = util.time.nowISO8601();

    const updates = ctx.args.ids.map((id, index) => ({
        id,
        rank: ctx.args.ranks[index],
    }));

    return {
        operation: 'BatchPutItem',
        tables: {
            [tableName]: updates.map((update) =>
                util.dynamodb.toMapValues({
                id: update.id,
                rank: update.rank,
                resumeID: ctx.args.resumeID,
                updatedAt: now,
                __typename: 'Group'
                })
            ),
        },
    };
}

export function response(ctx) {
    if (ctx.error) {
        util.error(ctx.error.message, ctx.error.type);
    }
    return ctx.result.data[`Group-${ctx.stash.awsAppsyncApiId}-${ctx.stash.amplifyApiEnvironmentName}`];
}

What I've tried:

Questions:

Environment:

Upvotes: 1

Views: 34

Answers (0)

Related Questions