sst.dev icon indicating copy to clipboard operation
sst.dev copied to clipboard

Add a Create Note API

Open OndeVai opened this issue 7 years ago • 1 comments

With serverless cli version 1.33.2.

The lambda function in the document at https://serverless-stack.com/chapters/add-a-create-note-api.html does not return any result to the console or create the item when calling "serverless invoke local --function create --path mocks/create-event.json". It only seems to work if the function is async and uses async await:

import uuid from "uuid";
import AWS from "aws-sdk";



export async function main(event, context, callback) {

    const dynamoDb = new AWS.DynamoDB.DocumentClient();
    // Request body is passed in as a JSON encoded string in 'event.body'
    const data = JSON.parse(event.body);

    const params = {
        TableName: "notes",
        // 'Item' contains the attributes of the item to be created
        // - 'userId': user identities are federated through the
        //             Cognito Identity Pool, we will use the identity id
        //             as the user id of the authenticated user
        // - 'noteId': a unique uuid
        // - 'content': parsed from request body
        // - 'attachment': parsed from request body
        // - 'createdAt': current Unix timestamp
        Item: {
            userId: event.requestContext.identity.cognitoIdentityId,
            noteId: uuid.v1(),
            content: data.content,
            attachment: data.attachment,
            createdAt: Date.now()
        }
    };

    const headers = {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Credentials": true
    };

    try {
        await dynamoDb.put(params).promise();
        return {
            statusCode: 200,
            headers: headers,
            body: JSON.stringify(params.Item)
        };
        return response;
    }
    catch(e){
        console.error(e);
        return {
            statusCode: 500,
            headers: headers,
            body: JSON.stringify({ status: false })
        };
    }
}

OndeVai avatar Nov 28 '18 22:11 OndeVai

That's weird because it was working fine in v1.32.0. And they had just updated it to support async functions.

jayair avatar Nov 29 '18 19:11 jayair