Last active
December 8, 2022 03:00
-
-
Save milancermak/ba8bb573df664adf412dd8baa20bf3be to your computer and use it in GitHub Desktop.
Custom session storage for a Shopify app in SQL using Prisma
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Thanks for sharing this, helped a lot! 🙏