tith
tith

Reputation: 3

How to run multi query in AppSync JS resolver?

I create an AppSync API. I use dynamodb single table to store data of classes and teachers. I have pk as partition key and sk as sort key. I also create GSI with name teacherByClass that have classId as partition key and teacherId as sort key.
I try to get teachers by class.

Here my table:
School table

my appsync js resolver

import { util } from '@aws-appsync/utils';

export const request = (ctx) => {
    const { pk, classId } = ctx.args;

    // Query to get the class
    const classQuery = {
        operation: 'GetItem',
        key: util.dynamodb.toMapValues({ pk: pk, sk: '#INFO' }),
    };

    // Query to get teachers for the specified classId
    const teachersQuery = {
        operation: 'Query',
        index: 'teacherByClass',
        query: {
            expression: 'classId = :classId',
            expressionValues: util.dynamodb.toMapValues({
                ':classId': classId,
            }),
        },
    };

    // Return both queries as an array
    return {classQuery, teachersQuery};
};


export const response = (ctx) => {
    const {result, error} = ctx;
    
    if(error){
        util.error(`Error: ${error}, Result: ${result}`);
    }
    
    const { classQuery, teachersQuery } = result;

    // Handle the class result
    if (!classQuery || !classQuery.result) {
        util.error('Error fetching class data');
        return null; // or handle it as you see fit
    }

    // Handle the teachers result
    const teachersResult = teachersQuery.result || [];

    // Construct the final response
    return {
        classId: classQuery.result.classId,
        className: classQuery.result.className,
        teachers: teachersResult.map((teacher) => ({
            classId: teacher.classId,
            name: teacher.name,
        })),
    };
};

my schema:

type ClassProps {
    classId: String
    className: String
}

type ClassWithTeachers {
    classId: String
    className: String
    teachers: [Teacher]
}

type Teacher {
    classId: String
    name: String
}

type Query {
    listCLasses: [ClassProps]
    getClass(pk: String!, sk: String!): ClassProps
    getTeacherByClass(pk: String!, classId: String!): ClassWithTeachers
}

schema {
    query: Query
}

Upvotes: 0

Views: 12

Answers (0)

Related Questions