- const eventBeforeImporting = Date.now();
- import {
- DynamoDBClient,
- GetItemCommand,
- PutItemCommand,
- } from "@aws-sdk/client-dynamodb";
-
- const TABLE_NAME = "";
- const TOKEN_ID = "";
-
- const initinfSDK = Date.now();
- const client = new DynamoDBClient();
-
- console.log("sdk init successful", Date.now() - initinfSDK);
-
- export const nowUnix = () => Math.floor(Date.now() / 1000);
-
- export async function getManagementTokenFromDB() {
- const startTime = Date.now();
-
- const command = new GetItemCommand({
- TableName: TABLE_NAME,
- Key: {
- "my-key-name": { S: TOKEN_ID as string },
- },
- });
- const result = await client.send(command);
- const duration = Date.now() - startTime;
- console.info(`GetToken Time READ FROM DYNO: ${duration}ms`);
-
- if (!result.Item) {
- console.info("No token found in DB.");
- return null;
- }
- const tokenValue = result.Item.tokenValue.S;
- const expiresAt = parseInt(result.Item.expiresAt.N as string);
- const now = nowUnix();
- const age = expiresAt - now;
- if (now >= expiresAt) {
- console.info("Token expired.");
- return null;
- }
- console.info(`Token is valid. Expires in ${age}s`); // remove log for prod and even some more top level logs
- return tokenValue;
- }
-
- export async function saveNewToken(token: string) {
- const expiresAt = nowUnix() + Math.floor(6.5 * 24 * 60 * 60); // 6.5 days
- const now = nowUnix();
-
- const command = new PutItemCommand({
- TableName: TABLE_NAME,
- Item: {
- "my-key-name": { S: TOKEN_ID as string },
- tokenValue: { S: token },
- createdAt: { N: String(now) },
- expiresAt: { N: String(expiresAt) },
- },
- });
- await client.send(command);
- console.info("New token saved to DB.");
- }