export type Callback<T> = (
txn: DrizzleTransactionScope,
context: Context,
) => T | Promise<T>;
export async function txnWithContext<T>(
context: Context,
callback: Callback<T>,
): Promise<T> {
return await db.transaction(async (txn) => {
await txn.execute(
sql`select set_config('rls.organisation_id', ${context.organisationId}, TRUE);`,
);
return callback(txn, context);
});
}
async function createFoo(tx: DrizzleTransactionScope, values: {name:string, age:number}) {
await tx.insert(schema.foo).values(values);
}
async function createBar(tx: DrizzleTransactionScope, values: {name:string}) {
await tx.insert(schema.bar).values(values);
}
async function createUserService() {
await txnWithContext({organisationId: 'test'}, async (tx, context) => {
await createFoo(tx, {name: 'John Doe', age: 30});
await createBar(tx, {name: 'Something Else'});
});
}
export type Callback<T> = (
txn: DrizzleTransactionScope,
context: Context,
) => T | Promise<T>;
export async function txnWithContext<T>(
context: Context,
callback: Callback<T>,
): Promise<T> {
return await db.transaction(async (txn) => {
await txn.execute(
sql`select set_config('rls.organisation_id', ${context.organisationId}, TRUE);`,
);
return callback(txn, context);
});
}
async function createFoo(tx: DrizzleTransactionScope, values: {name:string, age:number}) {
await tx.insert(schema.foo).values(values);
}
async function createBar(tx: DrizzleTransactionScope, values: {name:string}) {
await tx.insert(schema.bar).values(values);
}
async function createUserService() {
await txnWithContext({organisationId: 'test'}, async (tx, context) => {
await createFoo(tx, {name: 'John Doe', age: 30});
await createBar(tx, {name: 'Something Else'});
});
}