Skip to content

Instantly share code, notes, and snippets.

@pjlsergeant
Created February 19, 2024 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjlsergeant/3344388da618afcd425b02ee3bf86097 to your computer and use it in GitHub Desktop.
Save pjlsergeant/3344388da618afcd425b02ee3bf86097 to your computer and use it in GitHub Desktop.
Prisma / express-session simple integration
// 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