Last active
January 5, 2023 21:51
-
-
Save mpurdon/dfd24b2b41bd952e2d5be36477f5d72d to your computer and use it in GitHub Desktop.
Storing a message in TS with Typescript DynamoDB Document Client
This file contains 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
/** | |
* Store the message in dynamo | |
* | |
* @param creationDate | |
* @param context | |
*/ | |
const storeMessage = async ( | |
creationDate: Date, | |
context, | |
): Promise<{ creationDateString: string; pk: string }> => { | |
/** | |
* Convert all parameter values to string | |
* | |
* @param parameters | |
*/ | |
const normalizeParameters = (parameters) => { | |
const normalized = {}; | |
for (const [key, value] of Object.entries(parameters)) { | |
normalized[key] = value.toString(); | |
} | |
return normalized; | |
}; | |
logger.debug({ | |
message: 'storing message', | |
creationDate, | |
context, | |
}); | |
const handlerSegment = tracer.getSegment(); | |
const subsegment = handlerSegment.addNewSubsegment('storeMessage'); | |
tracer.setSegment(subsegment); | |
const { headers, requestContext, body } = context; | |
const creationDateString = creationDate.toISOString(); | |
const id = ulid(); | |
const pk = `MESSAGE#${id}`; | |
const messageItem = { | |
_pk: pk, | |
_sk: creationDateString, | |
_gsi1pk: `received#${creationDateString.substring(0, 10)}`, | |
_gsi1sk: pk, | |
requestId: requestContext.requestId, | |
traceId: headers['x-amzn-trace-id'].replace('Root=', ''), | |
status: 'received', | |
createdOn: creationDateString, | |
user10dlc: body.from, | |
client10dlc: body.to, | |
templateId: body.templateId || 'unspecified', | |
functionName: body.functionName || 'unspecified', | |
parameters: normalizeParameters(body.parameters), | |
originalBody: JSON.stringify(body), | |
history: [ | |
{ | |
status: 'received', | |
createdOn: creationDateString, | |
}, | |
], | |
}; | |
logger.debug({ | |
message: 'storing message', | |
messageItem, | |
}); | |
const input: PutCommandInput = { | |
TableName: process.env.SMSTable, | |
Item: messageItem, | |
}; | |
try { | |
await dbDocClient.put(input); | |
} catch (e) { | |
logger.error('could not save message', e); | |
} finally { | |
// Set the original segment as active | |
subsegment.close(); | |
tracer.setSegment(handlerSegment); | |
} | |
return { pk, creationDateString }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment