Created
February 19, 2024 05:31
-
-
Save pjlsergeant/3344388da618afcd425b02ee3bf86097 to your computer and use it in GitHub Desktop.
Prisma / express-session simple integration
This file contains hidden or 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
// Offensively simple shim on top of https://www.npmjs.com/package/connect-pg-simple | |
import { PrismaClient } from '@prisma/client'; | |
import connectPgSimple from 'connect-pg-simple'; | |
import session from 'express-session'; | |
import { format } from '@scaleleap/pg-format'; | |
type Debugger = (arg: Record<string, unknown>) => Promise<void>; | |
export const consoleDebugger: Debugger = async (payload) => { | |
console.dir(payload, { depth: null }); | |
}; | |
class ShimPool { | |
#_debugId: number = 0; | |
constructor( | |
public prisma: PrismaClient, | |
private debug: Debugger | undefined | |
) {} | |
async query(query: string, params: unknown[]) { | |
let debugId = 0; | |
if (this.debug) { | |
debugId = this.#_debugId++; | |
this.debug({ _: 'original', query, params, debugId }); | |
} | |
// pg to pg-format param markup | |
const reParam = query.replaceAll(/\$(\d)/g, '%$1$$L'); | |
// Escape the query | |
const safeQuery = format(reParam, ...params); | |
if (this.debug) this.debug({ _: 'newQuery', safeQuery, debugId }); | |
// Run and return it | |
const rows = await this.prisma.$queryRawUnsafe(safeQuery); | |
if (this.debug) this.debug({ _: 'results', rows, debugId }); | |
return { rows }; | |
} | |
} | |
export function sessionStore(prismaClient: PrismaClient, tableName: string, debug?: Debugger): session.Store { | |
const PgSession = connectPgSimple(session); | |
const pool = new ShimPool(prismaClient, debug); | |
return new PgSession({ pool: pool as any, tableName }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment