amazon-web-servicesserverlessdynamoose

How to use dynamoose in AWS AppSync JS resolver?


I want to use dynamoose in JavaScript resolver to make it work with GraphQL and DynamoDB.

I try to import dynamoose in function that I was created in serverless framework. but I got error when I run serverless deploy

createUser.js

'use strict';

const { getSuccessResponse } = require('../../helper/success');
const { getErrorResponse } = require('../../helper/error');

const { v4: uuidv4 } = require('uuid');
const { UsersModel } = require('../../Models/UserModel');

module.exports.main = async (event) => {
  try {
    const request = JSON.parse(event.body);
    const { name, email } = request;

    const result = await UsersModel.create({
      id: uuidv4(),
      name,
      email,
    });

    return getSuccessResponse(result);
  } catch (error) {
    console.log(error);
    return getErrorResponse(error);
  }
};

UserModel.js

const dynamoose = require('dynamoose');

const schema = new dynamoose.Schema(
  {
    id: {
      type: String,
      hashKey: true,
    },
    name: String,
    age: Number,
  },
  {
    timestamps: true,
  }
);

const UsersModel = dynamoose.model('aws-appsync-dynamoose-dev-users', schema, {
  create: false,
  throughput: {
    read: 5,
    write: 5,
  },
});
module.exports = { UsersModel };

Solution

  • You can not use external libraries inside of AppSync's JS resolvers. Here's a list of supported runtime features: https://docs.aws.amazon.com/appsync/latest/devguide/resolver-util-reference-js.html

    One way of doing this would be to create a Lambda function (where you can install dynamoose), and then use AppSync JS resolver to invoke that function. See here: https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-lambda-resolvers-js.html