Create db helper functions.
This commit is contained in:
55
api/models/db.js
Normal file
55
api/models/db.js
Normal 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,
|
||||
};
|
||||
Reference in New Issue
Block a user