Skip to content

Instantly share code, notes, and snippets.

@carlosvega20
Created September 27, 2023 13:57
Show Gist options
  • Save carlosvega20/88dee49a37637f65c839060847f395fd to your computer and use it in GitHub Desktop.
Save carlosvega20/88dee49a37637f65c839060847f395fd to your computer and use it in GitHub Desktop.
const { graphql, buildSchema } = require('graphql');
const { makeExecutableSchema } = require('graphql-tools');
const AWS = require('aws-sdk');
// Set up AWS DynamoDB
const dynamodb = new AWS.DynamoDB.DocumentClient();
const tableName = 'Items'; // Your DynamoDB table name
// Define your GraphQL schema
const typeDefs = `
type Item {
itemId: String!
name: String!
description: String
}
type Query {
getItem(itemId: String!): Item
}
type Mutation {
createItem(itemId: String!, name: String!, description: String): Item
updateItem(itemId: String!, name: String!, description: String): Item
deleteItem(itemId: String!): Item
}
`;
// Define resolvers for your schema
const resolvers = {
Query: {
getItem: async (_, { itemId }) => {
const params = {
TableName: tableName,
Key: { itemId },
};
const response = await dynamodb.get(params).promise();
return response.Item;
},
},
Mutation: {
createItem: async (_, args) => {
const params = {
TableName: tableName,
Item: args,
};
await dynamodb.put(params).promise();
return args;
},
updateItem: async (_, args) => {
const params = {
TableName: tableName,
Key: { itemId: args.itemId },
UpdateExpression: 'SET name = :name, description = :description',
ExpressionAttributeValues: {
':name': args.name,
':description': args.description || null,
},
ReturnValues: 'ALL_NEW',
};
const response = await dynamodb.update(params).promise();
return response.Attributes;
},
deleteItem: async (_, { itemId }) => {
const params = {
TableName: tableName,
Key: { itemId },
ReturnValues: 'ALL_OLD',
};
const response = await dynamodb.delete(params).promise();
return response.Attributes;
},
},
};
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
// Handler function for AWS Lambda
exports.handler = async (event) => {
const body = JSON.parse(event.body);
const response = await graphql(schema, body.query, null, null, body.variables);
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(response),
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment