Skip to content

Instantly share code, notes, and snippets.

@milancermak
Last active December 8, 2022 03:00
Show Gist options
  • Save milancermak/ba8bb573df664adf412dd8baa20bf3be to your computer and use it in GitHub Desktop.
Save milancermak/ba8bb573df664adf412dd8baa20bf3be to your computer and use it in GitHub Desktop.
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")
}
@rchampourlier
Copy link

Thanks for sharing this, helped a lot! 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment