Add a Create Note API

From @RobbingDaHood on Wed Jul 05 2017 04:22:39 GMT+0000 (UTC)

@jayair Sorry, I should have thought of that.

After I experienced this, then I saw the “Serverless ES7 Service”-page: http://serverless-stack.com/chapters/serverless-es7-service.html

So I permanently deleted everything and started over. It was so early in the development I had not put anything on Git yet, so I cannot find it in version control either.

When I used Serverless ES7 Service I did not need to make the change the “babel”-part to “babel-loader”.

From @jayair on Wed Jul 05 2017 17:08:49 GMT+0000 (UTC)

@RobbingDaHood Hmm interesting. I’ll see if I can replicate the issue.

From @d3sandoval on Sun Jul 09 2017 00:44:47 GMT+0000 (UTC)

Hi there,

I’m having similar issues as @martinsaporiti and @go4cas with babel. I have tried all the recommendations here to try to fix this error:

$ serverless webpack invoke --function create --path mocks/create-event.json
Serverless: WARNING: Plugin ServerlessWebpack uses deprecated hook before:deploy:createDeploymentArtifacts
Serverless: WARNING: Plugin ServerlessWebpack uses deprecated hook after:deploy:createDeploymentArtifacts
Serverless: Bundling with Webpack...
Time: 46ms
     Asset     Size  Chunks             Chunk Names
 create.js  3.27 kB       0  [emitted]  create
handler.js  1.93 kB       1  [emitted]  handler
Serverless: Run function create...
 
  Syntax Error -------------------------------------------
 
  Unexpected token import
 
     For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.
 
  Stack Trace --------------------------------------------
 
SyntaxError: Unexpected token import
/Users/admin/projects/notes-app-api/.webpack/create.js:47
        import uuid from 'uuid';
        ^^^^^^
SyntaxError: Unexpected token import
    at Object.exports.runInThisContext (vm.js:78:16)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at ServerlessWebpack.loadHandler (/Users/admin/projects/notes-app-api/node_modules/serverless-webpack/lib/run.js:21:20)
    at ServerlessWebpack.run (/Users/admin/projects/notes-app-api/node_modules/serverless-webpack/lib/run.js:61:26)
    at ServerlessWebpack.tryCatcher (/Users/admin/projects/notes-app-api/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/Users/admin/projects/notes-app-api/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/Users/admin/projects/notes-app-api/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/Users/admin/projects/notes-app-api/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/Users/admin/projects/notes-app-api/node_modules/bluebird/js/release/promise.js:693:18)
    at Promise._fulfill (/Users/admin/projects/notes-app-api/node_modules/bluebird/js/release/promise.js:638:18)
    at Promise._resolveCallback (/Users/admin/projects/notes-app-api/node_modules/bluebird/js/release/promise.js:432:57)
    at Promise._settlePromiseFromHandler (/Users/admin/projects/notes-app-api/node_modules/bluebird/js/release/promise.js:524:17)
    at Promise._settlePromise (/Users/admin/projects/notes-app-api/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/Users/admin/projects/notes-app-api/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/Users/admin/projects/notes-app-api/node_modules/bluebird/js/release/promise.js:693:18)
    at Promise._fulfill (/Users/admin/projects/notes-app-api/node_modules/bluebird/js/release/promise.js:638:18)
    at /Users/admin/projects/notes-app-api/node_modules/bluebird/js/release/nodeback.js:42:21
    at Compiler.<anonymous> (/Users/admin/projects/notes-app-api/node_modules/serverless-webpack/node_modules/webpack/lib/Compiler.js:194:14)
    at Compiler.emitRecords (/Users/admin/projects/notes-app-api/node_modules/serverless-webpack/node_modules/webpack/lib/Compiler.js:282:37)
    at Compiler.<anonymous> (/Users/admin/projects/notes-app-api/node_modules/serverless-webpack/node_modules/webpack/lib/Compiler.js:187:11)
    at /Users/admin/projects/notes-app-api/node_modules/serverless-webpack/node_modules/webpack/lib/Compiler.js:275:11
    at Compiler.applyPluginsAsync (/Users/admin/projects/notes-app-api/node_modules/tapable/lib/Tapable.js:60:69)
    at Compiler.afterEmit (/Users/admin/projects/notes-app-api/node_modules/serverless-webpack/node_modules/webpack/lib/Compiler.js:272:8)
    at Compiler.<anonymous> (/Users/admin/projects/notes-app-api/node_modules/serverless-webpack/node_modules/webpack/lib/Compiler.js:267:14)
    at /Users/admin/projects/notes-app-api/node_modules/async/lib/async.js:52:16
    at done (/Users/admin/projects/notes-app-api/node_modules/async/lib/async.js:246:17)
    at /Users/admin/projects/notes-app-api/node_modules/async/lib/async.js:44:16
    at /Users/admin/projects/notes-app-api/node_modules/graceful-fs/graceful-fs.js:43:10
    at /usr/local/lib/node_modules/serverless/node_modules/graceful-fs/graceful-fs.js:43:10
    at FSReqWrap.oncomplete (fs.js:112:15)
From previous event:
    at PluginManager.invoke (/usr/local/lib/node_modules/serverless/lib/classes/PluginManager.js:217:22)
    at PluginManager.run (/usr/local/lib/node_modules/serverless/lib/classes/PluginManager.js:236:17)
    at variables.populateService.then (/usr/local/lib/node_modules/serverless/lib/Serverless.js:107:33)
    at runCallback (timers.js:651:20)
    at tryOnImmediate (timers.js:624:5)
    at processImmediate [as _immediateCallback] (timers.js:596:5)
From previous event:
    at Serverless.run (/usr/local/lib/node_modules/serverless/lib/Serverless.js:94:74)
    at serverless.init.then (/usr/local/lib/node_modules/serverless/bin/serverless:30:50)
 
  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
     Forums:        forum.serverless.com
     Chat:          gitter.im/serverless/serverless
 
  Your Environment Information -----------------------------
     OS:                     darwin
     Node Version:           7.4.0
     Serverless Version:     1.16.1

My .babelrc:

{
  "plugins": ["transform-runtime"],
  "presets": ["es2015", "stage-3"]
}

My webpack.config.js (I’ve also tried using loader: 'babel-loader' instead of the loaders array in the module rules:

var glob = require('glob');
var path = require('path');
var nodeExternals = require('webpack-node-externals');

// Required for Create React App Babel transform
process.env.NODE_ENV = 'production';

module.exports = {
    // Use all js files in project root (except
    // the webpack config) as an entry
    entry: globEntries('!(webpack.config).js'),
    target: 'node',
    // Since 'aws-sdk' is not compatible with webpack,
    // we exclude all node dependencies
    externals: [nodeExternals()],
    // Run babel on all .js files and skip those in node_modules
    module: {
        rules: [{
            test: /\.js$/,
            loaders: ['babel-loader'],
            include: __dirname,
            exclude: /node_modules/,
        }]
    },
    // We are going to create multiple APIs in this guide, and we are
    // going to create a js file to for each, we need this output block
    output: {
        libraryTarget: 'commonjs',
        path: path.join(__dirname, '.webpack'),
        filename: '[name].js'
    },
};

function globEntries(globPath) {
    var files = glob.sync(globPath);
    var entries = {};

    for (var i = 0; i < files.length; i++) {
        var entry = files[i];
        entries[path.basename(entry, path.extname(entry))] = './' + entry;
    }

    return entries;
}

My package.json:

{
  "name": "notes-app-api",
  "version": "1.0.0",
  "description": "",
  "main": "handler.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "aws-sdk": "^2.80.0",
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-3": "^6.24.1",
    "glob": "^7.1.2",
    "serverless-webpack": "^1.0.0-rc.4",
    "webpack": "^3.1.0",
    "webpack-node-externals": "^1.6.0"
  },
  "dependencies": {
    "babel-runtime": "^6.23.0",
    "uuid": "^3.1.0"
  }
}

I have been following the steps from the beginning but took a break a few weeks ago before coming back to test my create.js file. Could something have changed in the upstream repositories since then?

Thanks in advance for any help

From @jayair on Sun Jul 09 2017 00:55:54 GMT+0000 (UTC)

@d3sandoval That sounds like the serverless-webpack plugin did not do it’s job. I’m just comparing your package.json to the one from this chapter and it seems like your serverless-webpack plugin is out of date. We did make some updates recently so that could be a reason why the one you have is old.

Try updating it and let me know if that fixes it.

From @d3sandoval on Sun Jul 09 2017 01:09:03 GMT+0000 (UTC)

That seemed to work! But now I’m getting the 500 error:

$ serverless webpack invoke --function create --path mocks/create-event.json
Serverless: WARNING: Plugin ServerlessWebpack uses deprecated hook before:deploy:createDeploymentArtifacts
Serverless: WARNING: Plugin ServerlessWebpack uses deprecated hook after:deploy:createDeploymentArtifacts
Serverless: Bundling with Webpack...
Time: 328ms
     Asset     Size  Chunks             Chunk Names
 create.js  5.19 kB       0  [emitted]  create
handler.js  3.02 kB       1  [emitted]  handler
   [0] ./create.js 1.77 kB {0} [built]
   [1] external "uuid" 42 bytes {0} [not cacheable]
   [2] external "aws-sdk" 42 bytes {0} [not cacheable]
   [3] ./handler.js 463 bytes {1} [built]
Serverless: Run function create...
{ statusCode: 500,
  headers: 
   { 'Access-Control-Allow-Origin': '*',
     'Access-Control-Allow-Credentials': true },
  body: '{"status":false}' }

Good call on updating to the latest. Not sure why npm update wouldn’t have caught that.

From @jayair on Sun Jul 09 2017 01:15:17 GMT+0000 (UTC)

@d3sandoval Try debugging it using these steps - http://serverless-stack.com/chapters/add-a-create-note-api.html#common-issues

From @d3sandoval on Sun Jul 09 2017 01:17:53 GMT+0000 (UTC)

@jayair good call :slight_smile: Typing is hard! Turns out nodeId =/= noteId. I’m getting the 200 response now!

From @peterschwarz21 on Thu Jul 20 2017 19:37:28 GMT+0000 (UTC)

I just have a question about CORS. Why do the headers “Access-Control-Allow-Origin” and the others need to be defined in both the YML and the Success method? Shouldn’t setting CORs to true in the YML take care of the pre-flight?

From @jayair on Thu Jul 20 2017 19:51:42 GMT+0000 (UTC)

@peterschwarz21 That’s a good question. By setting the cors: true we are telling API Gateway to respond to the OPTIONS preflight request for our API. And in the tutorial we want to control the headers that we are sending in our Lambda (we are using lambda-proxy integration). So we need to specify the Access-Control- headers ourselves. Here is some info on this - https://serverless.com/framework/docs/providers/aws/events/apigateway/#enabling-cors

From @peterschwarz21 on Thu Jul 20 2017 20:54:29 GMT+0000 (UTC)

Thanks for the quick reply! I think I got it now. You da best!

From @mikhaelbendavid on Thu Jul 20 2017 21:38:32 GMT+0000 (UTC)

Love the tutorial so far! I have an issue here though, it’s right at the point in the tutorial where you ask us to invoke the create function and check for 200/500 for the first time.

Getting an error saying the module build ‘failed’, 'Couldn’t find preset es-2015" relative to directory. My package.json seems to be fully up to date, here it is below:

From @mikhaelbendavid on Thu Jul 20 2017 22:19:20 GMT+0000 (UTC)

Nevermind, fixed it: In the babelrc file, I had to change the preset name from just ‘es-2015’ as the tutorial stated, to the full npm name ‘babel-preset-2015’.

From @jayair on Thu Jul 20 2017 23:00:59 GMT+0000 (UTC)

@mikhaelbendavid That’s really weird. The .babelrc is supposed to use es2015 as the preset. https://babeljs.io/docs/plugins/preset-es2015/#usage-via-babelrc-recommended-

Can I see your full .babelrc?

From @bharloe on Fri Jul 21 2017 03:27:06 GMT+0000 (UTC)

I believe there is a typo in the following sentence from this page: “We are going to expand more on where this id in the coming chapters when we set up our Cognito Identity Pool.”

From @jayair on Fri Jul 21 2017 17:01:40 GMT+0000 (UTC)

@bharloe Thank you!

From @mikhaelbendavid on Fri Jul 21 2017 18:49:50 GMT+0000 (UTC)

Jayair - here is my .babelrc - I’m still getting a 500 error code, so need to troubleshoot to get the 200 before I move on.

From @jayair on Fri Jul 21 2017 19:13:49 GMT+0000 (UTC)

@mikhaelbendavid Hmm just read your previous comment again. The preset is es2015 not es-2015. Not sure if that is the issue.

From @mikhaelbendavid on Fri Jul 21 2017 19:17:33 GMT+0000 (UTC)

Modified the preset to just be ‘es2015’, not full babel-preset-2015. Webpack is still working, but still getting 500 error - haven’t refactored the code yet, no sense in moving on until then.
Here’s the repo I’m using to track progress:

From @bharloe on Fri Jul 21 2017 19:47:05 GMT+0000 (UTC)

@mikhaelbendavid I ran your code and it works for me. If you edit your error response to look like this it will record the error for you:

//Return status code 500 on error
	if (error) {
		const response = {
			statusCode: 500,
			headers: headers,
			body: JSON.stringify({status:false}),
			error: error
		};
		callback(null, response);
		return;

I’m guessing you’re getting a 500 because it is not connecting to the dynamo db database. If that’s the case there’s 2 things to check. Make sure you have configured your code to be in the same region as your dynamo db database at the top of create.js. If that is set, then make sure you have the dynamodb database itself configured properly and that all the items match exactly what you have in the code. Keep in mind it is case sensitive, so if you have ‘userId’ in the params object, but in your database it is ‘userid’, you will get a 500 error.

1 Like

From @mikhaelbendavid on Fri Jul 21 2017 19:49:20 GMT+0000 (UTC)

@bharloe - You are exactly correct! The names of the userId and noteId were ‘userid’ and ‘notesid’ - sloppiness on my part. I just got a 200 code!