Skip to content

Instantly share code, notes, and snippets.

@milancermak

milancermak/app-session.ts

Last active Mar 15, 2021
Embed
What would you like to do?
Custom session storage for a Shopify app in SQL using Prisma
import { PrismaClient } from '@prisma/client'
import Shopify from '@shopify/shopify-api'
import { Session } from '@shopify/shopify-api/dist/auth/session';
const prisma = new PrismaClient({ log: ['info', 'warn', 'error'] })
async function storeCallback(session: Session): Promise<boolean> {
const payload: { [key: string]: any } = { ...session }
return prisma.appSession.upsert({
create: { id: session.id, payload: payload },
update: { payload: payload },
where: { id: session.id }
}).then(_ => {
return true
}).catch(err => {
return false
})
}
async function loadCallback(id: string): Promise<Session | undefined> {
return prisma.appSession.findUnique({
where: { id: id }
}).then(data => {
if (!data) {
return undefined
}
const session = new Session(data.id)
// @ts-ignore
const { shop, state, scope, accessToken, isOnline, expires, onlineAccessInfo } = data.payload
session.shop = shop
session.state = state
session.scope = scope
session.expires = expires ? new Date(expires) : undefined
session.isOnline = isOnline
session.accessToken = accessToken
session.onlineAccessInfo = onlineAccessInfo
return session
}).catch(err => {
return undefined
})
}
async function deleteCallback(id: string): Promise<boolean> {
return prisma.appSession.delete({
where: { id: id }
}).then(_ => {
return true
}).catch(err => {
return false
})
}
export const SqlSessionStorage = new Shopify.Session.CustomSessionStorage(
storeCallback,
loadCallback,
deleteCallback,
)
model AppSession {
id String @id
payload Json
@@map("app_session")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment