Last active
April 20, 2020 08:46
-
-
Save mikehibm/c5f667103304f4c26b3a8437f9168cf6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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