Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import dynamoStore = require('dynamodb-datastore');
import cdk = require('@aws-cdk/core');
import lambda = require('@aws-cdk/aws-lambda');
const app = new cdk.App();
class MyStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
this.datastore = new dynamoStore.DataStoreConstruct(this, 'my-datastore');
this.datastore.addObjectType('User', {
indexes: [
'id',
'username',
'email'
]
});
this.userLamda = .Function(this, 'Singleton', {
code: new lambda.InlineCode(fs.readFileSync('lambda.js', { encoding: 'utf-8' })),
handler: 'index.handler',
timeout: cdk.Duration.seconds(300),
runtime: lambda.Runtime.JAVASCRIPT,
env: {
DATASTORE_TABLE_NAME: this.datastore.tableName
}
});
// Helper method similar to the native CDK table.grantReadWriteData(iamRoleBearer)
// but aware of the object types, and generates the right IAM statements
this.datastore.grantReadWriteType('User').to(this.userLambda);
}
}
app.synth();
// In my Lambda:
const dynamoStore = require('dynamodb-datastore');
// Interface that exposes higher level methods that
// automatically generate DynamoDB queries with queries
// that use the right primary key prefix
myDatastore = new dynamoStore.DataStoreInterface({
tableName: process.env.DATASTORE_TABLE_NAME
})
exports.handler = async function(event, context) {
await myDatastore.writeObject({
type: 'User',
object: {
id: 1,
username: 'foo',
email: 'foo@bar.com'
}
}
let userFoundById = await myDatastore.findObject({
type: 'User',
match: {
id: 1
}
});
let userFoundByUsername = await myDatastore.findObject({
type: 'User',
match: {
username: 'foo'
}
});
let userFoundByEmail = await myDatastore.findObject({
type: 'User',
match: {
email: 'foo@bar.com'
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment