@shopify/shopify-app-session-storage-dynamodb
Version:
Shopify App Session Storage for DynamoDB
87 lines (83 loc) • 3.09 kB
JavaScript
;
var clientDynamodb = require('@aws-sdk/client-dynamodb');
var utilDynamodb = require('@aws-sdk/util-dynamodb');
var shopifyApi = require('@shopify/shopify-api');
const defaultDynamoDBSessionStorageOptions = {
sessionTableName: 'shopify_sessions',
shopIndexName: 'shop_index',
};
class DynamoDBSessionStorage {
client;
options;
constructor(opts) {
this.options = { ...defaultDynamoDBSessionStorageOptions, ...opts };
this.client = new clientDynamodb.DynamoDBClient({ ...this.options.config });
}
async storeSession(session) {
await this.client.send(new clientDynamodb.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 clientDynamodb.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 clientDynamodb.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 clientDynamodb.QueryCommand({
TableName: this.options.sessionTableName,
IndexName: this.options.shopIndexName,
KeyConditionExpression: 'shop = :shop',
ExpressionAttributeValues: utilDynamodb.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 utilDynamodb.marshall({ id });
}
deserializeId(id) {
return utilDynamodb.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 utilDynamodb.marshall(rawSession, {
removeUndefinedValues: true,
});
}
deserializeSession(session) {
const rawSession = utilDynamodb.unmarshall(session);
// Convert the ISO string back to a Date object
return new shopifyApi.Session({
...rawSession,
expires: rawSession.expires ? new Date(rawSession.expires) : undefined,
});
}
}
exports.DynamoDBSessionStorage = DynamoDBSessionStorage;
//# sourceMappingURL=dynamodb.js.map