Snippet content copied to clipboard.
Are you sure to delete this snippet? No, don't delete
  1. const eventBeforeImporting = Date.now();
  2. import {
  3. DynamoDBClient,
  4. GetItemCommand,
  5. PutItemCommand,
  6. } from "@aws-sdk/client-dynamodb";
  7. const TABLE_NAME = "";
  8. const TOKEN_ID = "";
  9. const initinfSDK = Date.now();
  10. const client = new DynamoDBClient();
  11. console.log("sdk init successful", Date.now() - initinfSDK);
  12. export const nowUnix = () => Math.floor(Date.now() / 1000);
  13. export async function getManagementTokenFromDB() {
  14. const startTime = Date.now();
  15. const command = new GetItemCommand({
  16. TableName: TABLE_NAME,
  17. Key: {
  18. "my-key-name": { S: TOKEN_ID as string },
  19. },
  20. });
  21. const result = await client.send(command);
  22. const duration = Date.now() - startTime;
  23. console.info(`GetToken Time READ FROM DYNO: ${duration}ms`);
  24. if (!result.Item) {
  25. console.info("No token found in DB.");
  26. return null;
  27. }
  28. const tokenValue = result.Item.tokenValue.S;
  29. const expiresAt = parseInt(result.Item.expiresAt.N as string);
  30. const now = nowUnix();
  31. const age = expiresAt - now;
  32. if (now >= expiresAt) {
  33. console.info("Token expired.");
  34. return null;
  35. }
  36. console.info(`Token is valid. Expires in ${age}s`); // remove log for prod and even some more top level logs
  37. return tokenValue;
  38. }
  39. export async function saveNewToken(token: string) {
  40. const expiresAt = nowUnix() + Math.floor(6.5 * 24 * 60 * 60); // 6.5 days
  41. const now = nowUnix();
  42. const command = new PutItemCommand({
  43. TableName: TABLE_NAME,
  44. Item: {
  45. "my-key-name": { S: TOKEN_ID as string },
  46. tokenValue: { S: token },
  47. createdAt: { N: String(now) },
  48. expiresAt: { N: String(expiresAt) },
  49. },
  50. });
  51. await client.send(command);
  52. console.info("New token saved to DB.");
  53. }

Edit this Snippet