Skip to content

Commit

Permalink
initial checkin, backend code finished
Browse files Browse the repository at this point in the history
  • Loading branch information
bscaspar committed Nov 4, 2018
0 parents commit 0445617
Show file tree
Hide file tree
Showing 23 changed files with 10,144 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"plugins": ["source-map-support", "transform-runtime"],
"presets": [
["env", { "node": "8.10" }],
"stage-3"
]
}

52 changes: 52 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules
jspm_packages

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history

# vim
.*.sw*
Session.vim

# Serverless
.webpack
.serverless

# env
env.yml
.env

# Jetbrains IDEs
.idea
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017 Anomaly Innovations

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
131 changes: 131 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
# Serverless Node.js Starter

A Serverless starter that adds ES7 syntax, serverless-offline, environment variables, and unit test support. Part of the [Serverless Stack](http://serverless-stack.com) guide.

[Serverless Node.js Starter](https://github.com/AnomalyInnovations/serverless-nodejs-starter) uses the [serverless-webpack](https://github.com/serverless-heaven/serverless-webpack) plugin, [Babel](https://babeljs.io), [serverless-offline](https://github.com/dherault/serverless-offline), and [Jest](https://facebook.github.io/jest/). It supports:

- **ES7 syntax in your handler functions**
- Use `import` and `export`
- **Package your functions using Webpack**
- **Run API Gateway locally**
- Use `serverless offline start`
- **Support for unit tests**
- Run `npm test` to run your tests
- **Sourcemaps for proper error messages**
- Error message show the correct line numbers
- Works in production with CloudWatch
- **Automatic support for multiple handler files**
- No need to add a new entry to your `webpack.config.js`
- **Add environment variables for your stages**

---

### Demo

A demo version of this service is hosted on AWS - [`https://z6pv80ao4l.execute-api.us-east-1.amazonaws.com/dev/hello`](https://z6pv80ao4l.execute-api.us-east-1.amazonaws.com/dev/hello)

And here is the ES7 source behind it

``` javascript
export const hello = async (event, context, callback) => {
const response = {
statusCode: 200,
body: JSON.stringify({
message: `Go Serverless v1.0! ${(await message({ time: 1, copy: 'Your function executed successfully!'}))}`,
input: event,
}),
};

callback(null, response);
};

const message = ({ time, ...rest }) => new Promise((resolve, reject) =>
setTimeout(() => {
resolve(`${rest.copy} (with a delay)`);
}, time * 1000)
);
```

### Requirements

- [Install the Serverless Framework](https://serverless.com/framework/docs/providers/aws/guide/installation/)
- [Configure your AWS CLI](https://serverless.com/framework/docs/providers/aws/guide/credentials/)

### Installation

To create a new Serverless project.

``` bash
$ serverless install --url https://github.com/AnomalyInnovations/serverless-nodejs-starter --name my-project
```

Enter the new directory

``` bash
$ cd my-project
```

Install the Node.js packages

``` bash
$ npm install
```

### Usage

To run unit tests on your local

``` bash
$ npm test
```

To run a function on your local

``` bash
$ serverless invoke local --function hello
```

To simulate API Gateway locally using [serverless-offline](https://github.com/dherault/serverless-offline)

``` bash
$ serverless offline start
```

Run your tests

``` bash
$ npm test
```

We use Jest to run our tests. You can read more about setting up your tests [here](https://facebook.github.io/jest/docs/en/getting-started.html#content).

Deploy your project

``` bash
$ serverless deploy
```

Deploy a single function

``` bash
$ serverless deploy function --function hello
```

To add another function as a new file to your project, simply add the new file and add the reference to `serverless.yml`. The `webpack.config.js` automatically handles functions in different files.

To add environment variables to your project

1. Rename `env.example` to `env.yml`.
2. Add environment variables for the various stages to `env.yml`.
3. Uncomment `environment: ${file(env.yml):${self:provider.stage}}` in the `serverless.yml`.
4. Make sure to not commit your `env.yml`.

### Support

- Send us an [email](mailto:[email protected]) if you have any questions
- Open a [new issue](https://github.com/AnomalyInnovations/serverless-nodejs-starter/issues/new) if you've found a bug or have some suggestions.
- Or submit a pull request!

### Maintainers

Serverless Node.js Starter is maintained by Frank Wang ([@fanjiewang](https://twitter.com/fanjiewang)) & Jay V ([@jayair](https://twitter.com/jayair)). [**Subscribe to our newsletter**](http://eepurl.com/cEaBlf) for updates. Send us an [email](mailto:[email protected]) if you have any questions.
29 changes: 29 additions & 0 deletions create.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import uuid from 'uuid';
import AWS from 'aws-sdk';

import * as dynamoDbLib from './libs/dynamodb-libs';
import { success, failure } from './libs/response-lib';

AWS.config.update({ region: "us-west-2" });

export async function main(event, context) {
const data = JSON.parse(event.body);
const params = {
TableName: "notes",
Item: {
userId: event.requestContext.identity.cognitoIdentityId,
noteId: uuid.v1(),
content: data.content,
attachment: data.attachment,
createdAt: Date.now()
}
};

try {
await dynamoDbLib.call("put", params);
return success(params.Item);
} catch (e) {
console.log(e);
return failure({ status: false });
}
}
19 changes: 19 additions & 0 deletions delete.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import * as dynamoDbLib from './libs/dynamodb-libs';
import { success, failure } from './libs/response-lib';

export async function main(event, context) {
const params = {
TableName: "notes",
Key: {
userId: event.requestContext.identity.cognitoIdentityId,
noteId: event.pathParameters.id
}
};

try {
const result = await dynamoDbLib.call("delete", params);
return success({ status: true });
} catch (e) {
return failure({ status: false })
}
}
12 changes: 12 additions & 0 deletions env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# HOW TO USE:
#
# 1 Add environment variables for the various stages here
# 2 Rename this file to env.yml and uncomment it's usage
# in the serverless.yml.
# 3 Make sure to not commit this file.

dev:
APP_NAME: serverless-nodejs-starter

prod:
APP_NAME: serverless-nodejs
23 changes: 23 additions & 0 deletions get.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as dynamoDbLib from './libs/dynamodb-libs';
import { success, failure } from './libs/response-lib';

export async function main(event, context) {
const params = {
TableName: "notes",
Key: {
userId: event.requestContext.identity.cognitoIdentityId,
noteId: event.pathParameters.id
}
};

try {
const result = await dynamoDbLib.call("get", params);
if(result.Item) {
return success(result.Item)
} else {
return failure({ status: false, error: "Item not found."})
}
} catch (e) {
return failure({ status: false })
}
}
16 changes: 16 additions & 0 deletions handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export const hello = async (event, context, callback) => {
const response = {
statusCode: 200,
body: JSON.stringify({
message: `Go Serverless v1.0! ${(await message({ time: 1, copy: 'Your function executed successfully!'}))}`,
}),
};

callback(null, response);
};

const message = ({ time, ...rest }) => new Promise((resolve, reject) =>
setTimeout(() => {
resolve(`${rest.copy} (with a delay)`);
}, time * 1000)
);
7 changes: 7 additions & 0 deletions libs/dynamodb-libs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import AWS from 'aws-sdk';

export function call(action, params) {
const dynamoDb = new AWS.DynamoDB.DocumentClient();

return dynamoDb[action](params).promise();
}
18 changes: 18 additions & 0 deletions libs/response-lib.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export function success(body) {
return buildResponse(200, body);
}

export function failure(body) {
return buildResponse(500, body);
}

function buildResponse(statusCode, body) {
return {
statusCode: statusCode,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true
},
body: JSON.stringify(body)
}
}
19 changes: 19 additions & 0 deletions list.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import * as dynamoDbLib from './libs/dynamodb-libs';
import { success, failure } from './libs/response-lib';

export async function main(event, context) {
const params = {
TableName: "notes",
KeyConditionExpression: "userId = :userId",
ExpressionAttributeValues: {
":userId": event.requestContext.identity.cognitoIdentityId
}
}

try {
const result = await dynamoDbLib.call("query", params);
return success(result.Items);
} catch (e) {
return failure({ status: false })
}
}
8 changes: 8 additions & 0 deletions mocks/create-event.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"body": "{\"content\":\"hello world\",\"attachment\":\"hello.jpg\"}",
"requestContext": {
"identity": {
"cognitoIdentityId": "USER-SUB-1234"
}
}
}
10 changes: 10 additions & 0 deletions mocks/delete-event.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"pathParameters": {
"id": "89e74e50-df08-11e8-8e64-a921e1cdd133"
},
"requestContext": {
"identity": {
"cognitoIdentityId": "USER-SUB-1234"
}
}
}
Loading

0 comments on commit 0445617

Please sign in to comment.