UNPKG

@shopify/shopify-app-session-storage-dynamodb

Version:
85 lines (82 loc) 2.97 kB
import { DynamoDBClient, PutItemCommand, GetItemCommand, DeleteItemCommand, QueryCommand } from '@aws-sdk/client-dynamodb'; import { marshall, unmarshall } from '@aws-sdk/util-dynamodb'; import { Session } from '@shopify/shopify-api'; const defaultDynamoDBSessionStorageOptions = { sessionTableName: 'shopify_sessions', shopIndexName: 'shop_index', }; class DynamoDBSessionStorage { client; options; constructor(opts) { this.options = { ...defaultDynamoDBSessionStorageOptions, ...opts }; this.client = new DynamoDBClient({ ...this.options.config }); } async storeSession(session) { await this.client.send(new PutItemCommand({ TableName: this.options.sessionTableName, Item: this.serializeSession(session), })); return true; } async loadSession(id) { if (!id) return undefined; const result = await this.client.send(new GetItemCommand({ TableName: this.options.sessionTableName, Key: this.serializeId(id), })); return result.Item ? this.deserializeSession(result.Item) : undefined; } async deleteSession(id) { await this.client.send(new DeleteItemCommand({ TableName: this.options.sessionTableName, Key: this.serializeId(id), })); return true; } async deleteSessions(ids) { await Promise.all(ids.map((id) => this.deleteSession(id))); return true; } async findSessionsByShop(shop) { const result = await this.client.send(new QueryCommand({ TableName: this.options.sessionTableName, IndexName: this.options.shopIndexName, KeyConditionExpression: 'shop = :shop', ExpressionAttributeValues: marshall({ ':shop': shop, }), ProjectionExpression: 'id, shop', })); const sessions = await Promise.all(result.Items?.map((item) => this.loadSession(this.deserializeId(item))) || []); return sessions.filter((session) => session !== undefined); } serializeId(id) { return marshall({ id }); } deserializeId(id) { return unmarshall(id).id; } serializeSession(session) { // DynamoDB doesn't support Date objects, so we need to convert it to an ISO string const rawSession = { ...session.toObject(), expires: session.expires?.toISOString(), }; return marshall(rawSession, { removeUndefinedValues: true, }); } deserializeSession(session) { const rawSession = unmarshall(session); // Convert the ISO string back to a Date object return new Session({ ...rawSession, expires: rawSession.expires ? new Date(rawSession.expires) : undefined, }); } } export { DynamoDBSessionStorage }; //# sourceMappingURL=dynamodb.mjs.map