- Create the project from the following template:
$ sls create --template-url https://github.com/danteinc/js-cloud-native-cookbook/tree/master/ch2/event-first --path cncb-event-first
- Navigate to the cncb-event-first directory with cd cncb-event-first.
- Review the file named serverless.yml with the following content:
service: cncb-event-first
provider:
name: aws
runtime: nodejs8.10
iamRoleStatements:
- Effect: Allow
Action:
- kinesis:PutRecord
Resource: ${cf:cncb-event-stream-${opt:stage}.streamArn}
functions:
submit:
handler: handler.submit
environment:
STREAM_NAME: ${cf:cncb-event-stream-${opt:stage}.streamName}
- Review the file named handler.js with the following content:
module.exports.submit = (thing, context, callback) => {
thing.id = thing.id || uuid.v4();
const event = {
type: 'thing-submitted',
id: uuid.v1(),
partitionKey: thing.id,
timestamp: Date.now(),
tags: {
region: process.env.AWS_REGION,
kind: thing.kind,
},
thing: thing,
};
const params = {
StreamName: process.env.STREAM_NAME,
PartitionKey: event.partitionKey,
Data: Buffer.from(JSON.stringify(event)),
};
const kinesis = new aws.Kinesis();
kinesis.putRecord(params, (err, resp) => {
callback(err, event);
});
};
- Install the dependencies with npm install.
- Run the tests with npm test -- -s $MY_STAGE.
- Review the contents generated in the .serverless directory.
- Deploy the stack:
$ npm run dp:lcl -- -s $MY_STAGE
> cncb-event-first@1.0.0 dp:lcl <path-to-your-workspace>/cncb-event-first
> sls deploy -v -r us-east-1 "-s" "john"
Serverless: Packaging service...
...
Serverless: Stack update finished...
...
functions:
submit: cncb-event-first-john-submit
...
- Review the stack and function in the AWS Console.
- Invoke the submit function with the following command:
$ sls invoke -f submit -r us-east-1 -s $MY_STAGE -d '{"id":"11111111-1111-1111-1111-111111111111","name":"thing one","kind":"other"}'
{
"type": "thing-submitted",
"id": "2a1f5290-42c0-11e8-a06b-33908b837f8c",
"partitionKey": "11111111-1111-1111-1111-111111111111",
"timestamp": 1524025374265,
"tags": {
"region": "us-east-1",
"kind": "other"
},
"thing": {
"id": "11111111-1111-1111-1111-111111111111",
"name": "thing one",
"kind": "other"
}
}
- Take a look at the logs:
$ sls logs -f submit -r us-east-1 -s $MY_STAGE
START ...
2018-04-18 00:22:54 ... params: {"StreamName":"john-cncb-event-stream-s1","PartitionKey":"11111111-1111-1111-1111-111111111111","Data":{"type":"Buffer","data":[...]}}
2018-04-18 00:22:54 ... response: {"ShardId":"shardId-000000000000","SequenceNumber":"4958...2466"}
END ...
REPORT ... Duration: 381.21 ms Billed Duration: 400 ms ... Max Memory Used: 34 MB
- Remove the stack once you have finished with npm run rm:lcl -- -s $MY_STAGE.