Skip to content

Instantly share code, notes, and snippets.

@mikehibm
Last active April 20, 2020 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikehibm/c5f667103304f4c26b3a8437f9168cf6 to your computer and use it in GitHub Desktop.
Save mikehibm/c5f667103304f4c26b3a8437f9168cf6 to your computer and use it in GitHub Desktop.
const AWS = require('aws-sdk');
var awsServerlessExpressMiddleware = require('aws-serverless-express/middleware');
var bodyParser = require('body-parser');
var express = require('express');
//(中略)
const userIdPresent = true;
const partitionKeyName = 'pk';
const partitionKeyType = 'S';
const sortKeyName = 'sk';
const sortKeyType = 'S';
//(中略)
app.get(path + hashKeyPath, function (req, res) {
var condition = {};
condition[partitionKeyName] = {
ComparisonOperator: 'EQ',
};
if (userIdPresent && req.apiGateway) {
condition[partitionKeyName]['AttributeValueList'] = [
`${userIdPrefix}${req.apiGateway.event.requestContext.identity.cognitoIdentityId}` ||
UNAUTH,
];
} else {
try {
condition[partitionKeyName]['AttributeValueList'] = [
convertUrlType(
`${userIdPrefix}${req.params[partitionKeyName]}`,
partitionKeyType
),
];
} catch (err) {
res.statusCode = 500;
res.json({ error: 'Wrong column type ' + err });
}
}
let queryParams = {
TableName: tableName,
KeyConditions: condition,
};
dynamodb.query(queryParams, (err, data) => {
if (err) {
res.statusCode = 500;
res.json({ error: 'Could not load items: ' + err });
} else {
const todos = mapDbToTodoModel(data.Items);
res.json(todos);
}
});
});
//(中略)
app.post(path, function (req, res) {
const item = mapTodoModelToDb(req);
item[sortKeyName] = `${todoIdPrefix}${getNewId()}`;
let putItemParams = {
TableName: tableName,
Item: item,
};
dynamodb.put(putItemParams, (err, data) => {
if (err) {
res.statusCode = 500;
res.json({ error: err, url: req.url, body: req.body });
} else {
res.json({ success: 'post call succeed!', url: req.url, data: data });
}
});
});
//(以下略)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment