@shopify/shopify-app-session-storage-kv
Version:
Shopify App Session Storage for KV
62 lines (59 loc) • 2.06 kB
JavaScript
import { Session } from '@shopify/shopify-api';
class KVSessionStorage {
namespace;
constructor(namespace) {
if (namespace) {
this.setNamespace(namespace);
}
}
setNamespace(namespace) {
this.namespace = namespace;
}
async storeSession(session) {
await this.namespace.put(session.id, JSON.stringify(session.toPropertyArray()));
await this.addShopIds(session.shop, [session.id]);
return true;
}
async loadSession(id) {
const sessionData = await this.namespace.get(id, 'json');
return sessionData ? Session.fromPropertyArray(sessionData) : undefined;
}
async deleteSession(id) {
const session = await this.loadSession(id);
if (!session) {
return true;
}
await this.namespace.delete(id);
await this.removeShopIds(session.shop, [session.id]);
return true;
}
async deleteSessions(ids) {
let result = true;
for (const id of ids) {
result = result && (await this.deleteSession(id));
}
return result;
}
async findSessionsByShop(shop) {
const sessionIds = await this.namespace.get(this.getShopSessionIdsKey(shop), { type: 'json' });
if (!sessionIds) {
return [];
}
return Promise.all(sessionIds.map(async (id) => (await this.loadSession(id))));
}
getShopSessionIdsKey(shop) {
return `shop:${shop}`;
}
async addShopIds(shop, ids) {
const key = this.getShopSessionIdsKey(shop);
const shopIds = (await this.namespace.get(key, 'json')) ?? [];
await this.namespace.put(key, JSON.stringify([...shopIds, ...ids]));
}
async removeShopIds(shop, ids) {
const key = this.getShopSessionIdsKey(shop);
const shopIds = (await this.namespace.get(key, 'json')) ?? [];
await this.namespace.put(key, JSON.stringify(shopIds.filter((id) => !ids.includes(id))));
}
}
export { KVSessionStorage };
//# sourceMappingURL=kv.mjs.map