-
Notifications
You must be signed in to change notification settings - Fork 1
/
get.mjs
73 lines (68 loc) · 2.65 KB
/
get.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { DynamoDB } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb";
import { createResponse } from '/opt/nodejs/sample-layer/utils.mjs';
const dynamodb = DynamoDBDocument.from(new DynamoDB({}));
const TABLE_NAME = process.env.TABLE_NAME;
const DDB_GSI_NAME = process.env.DDB_GSI_NAME;
let corsHeaders = {
'Access-Control-Allow-Origin': process.env.CORS_ORIGIN,
'Access-Control-Allow-Credentials': true,
};
export const handler = async (event) => {
return new Promise(async (resolve) => {
// to query the object, we require either the dataOwner and objectId (base table query),
// or the objectId (index query).
let getParams;
let queryParams;
if (event.queryStringParameters.dataOwner) {
// if we have the partition and sort keys, we can "get" the object directly
getParams = {
TableName: TABLE_NAME,
Key: {
"dataOwner": event.queryStringParameters.dataOwner,
"objectId": event.pathParameters.objectId
}
};
// or we can query the base table
queryParams = {
TableName: TABLE_NAME,
KeyConditionExpression: 'dataOwner = :owner_id and objectId = :obj_id',
ExpressionAttributeValues: {
':owner_id': event.queryStringParameters.dataOwner,
':obj_id': event.pathParameters.objectId
}
};
} else {
// if we don't have both partition and sort keys, we must query using an
// appropriate secondary index
console.log(`querying table index`);
queryParams = {
TableName: TABLE_NAME,
IndexName: DDB_GSI_NAME,
KeyConditionExpression: 'objectId = :obj_id',
ExpressionAttributeValues: { ':obj_id': event.pathParameters.objectId }
};
}
try {
const result = getParams ?
await dynamodb.get(getParams) :
await dynamodb.query(queryParams);
resolve(createResponse({
"statusCode": 200,
"headers": corsHeaders,
"body": result
}));
} catch (err) {
console.error(err);
resolve(createResponse({
"statusCode": 500,
"headers": corsHeaders,
"body": {
"success": false,
"reason": "an unexpected error occurred",
"error": err
}
}));
}
});
}