Create db helper functions.

This commit is contained in:
2020-11-01 21:06:59 -06:00
parent b758b85b15
commit 7002e78aa0
3 changed files with 64 additions and 45 deletions

55
api/models/db.js Normal file
View File

@@ -0,0 +1,55 @@
const AWS = require(`aws-sdk`);
const shortid = require(`shortid`);
const dynamodb = new AWS.DynamoDB.DocumentClient({
region: process.env.AWS_REGION
});
const defaultParams = {
TableName: process.env.db,
};
const put = async (kind, item) => {
const params = {
...defaultParams,
Item: {
...item,
sk: kind,
sk2: shortid.generate(),
createdAt: Date.now(),
updatedAt: Date.now(),
}
};
await dynamodb.put(params).promise();
};
const getByKey = async (key) => {
const params = {
...defaultParams,
KeyConditionExpression: `hk = :hk`,
ExpressionAttributeValues: { ':hk': key }
};
return await dynamodb.query(params).promise();
};
const getById = async (type, id) => {
const params = {
...defaultParams,
IndexName: process.env.dbIndex1,
KeyConditionExpression: `sk2 = :sk2 and sk = :sk`,
ExpressionAttributeValues: {
':sk2': id,
':sk': type,
}
};
return await dynamodb.query(params).promise();
};
module.exports = {
put,
getByKey,
getById,
};