lk-collection
Implement collections in an lk stack (Lambda, Kinesis + MongoDB).
TODO: transaction id
How it works
The library allows creating a collection object which has attached two lambda functions:
-
apiGatewayToKinesis
: takes a request from API Gateway and publishes an event to a Kinesis stream -
kinesisToMongodb
: takes kinesis events and projects them into a mongodb collection
Application event format
The data
property can be any JSON document.
Collection events
Insert
Client -> API Gateway:
POST /collection-name HTTP/1.1
Host: api-gateway.amazon.com
Content-Type: application/json
X-Token: authToken
{
"elementKey": "elementValue"
}
API Gateway -> Lambda:
Lambda -> Kinesis -> Lambda:
Lambda -> MongoDB: Inserted document:
Remove
Client -> API Gateway:
DELETE /collection-name/elementId HTTP/1.1
Host: api-gateway.amazon.com
X-Token: authToken
API Gateway -> Lambda:
Lambda -> Kinesis -> Lambda:
Lambda -> MongoDB Removed document:
Replace
Client -> API Gateway:
PUT /collection-name/elementId HTTP/1.1
Host: api-gateway.amazon.com
Content-Type: application/json
X-Token: authToken
{
"elementKey": "replacedValue"
}
API Gateway -> Lambda:
Lambda -> Kinesis -> Lambda:
Lambda -> MongoDB Updated document:
Example usage
/* Lambda function invoked by API Gateway */; const myCollection = name: "myCollectionName" mongodbUrl: "mongodb://myMongoHost/myDb" schema: $schema: "http://json-schema.org/draft-04/schema#" type: "object" { if Math > 05 throw 400 "Message" "Details"; } kinesisStreamName: "myStream"; const handler = myCollectionapiGatewayToKinesis;
/* Lambda function invoked by Kinesis */; const myCollection = name: "myCollectionName" mongodbUrl: "mongodb://myMongoHost/myDb"; const handler = myCollectionkinesisToMongodb;
Authorization
It's possible to pass the constructor an authorizeApiRequest
function which
either:
- returns a value
- throws
- returns a promise
The validation is considered successful (hence the request is handled) if:
- the
authorizeApiRequest
function returns a value - the
authorizeApiRequest
function returns a promise which is eventually resolved
The validation is considered unsuccessful (hence the request is rejected) if:
- the
authorizeApiRequest
function throws - the
authorizeApiRequest
function returns a promise which is eventually rejected
If the error thrown / promise reject value is an instance of RequestError
(import {RequestError} from "lk-collection"
), then that error is used as
error of the request. Otherwise a generic
{code: 500, message: "Internal server error"}
is used.