Skip to content

Instantly share code, notes, and snippets.

@jednano
Created April 5, 2021 20:45
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 jednano/058a9419934294f594a5c4b7382710ba to your computer and use it in GitHub Desktop.
Save jednano/058a9419934294f594a5c4b7382710ba to your computer and use it in GitHub Desktop.
Use Prisma Client Once
class PrismaClient {
#used = false;
/**
* Indicates whether `useOnce` has already been called.
*/
public get used() {
return this.#used;
}
/**
* Executes `callback` and safely disconnects the client after use via a
* try...finally expression, after which `this.used` will forever be `true`.
* @param callback Use a function expression to preserve lexical `this` context.
* Do not use an arrow function, as it overwrites lexical `this`.
* @throws `Error('client is already used')`
*/
public async useOnce(
callback: (
this: Omit<this, 'disconnect' | 'used' | 'useOnce'>
) => Promise<void>
) {
if (this.used) {
throw new Error('client is already used')
}
this.#used = true;
try {
await callback.call(this);
} finally {
return this.disconnect();
}
}
}
new PrismaClient().useOnce(async function() {
const post = await this.post.update({
where: { id: 1 },
data: { published: true }
});
console.log(post);
});
const client2 = new PrismaClient();
client2.used; // false
client2.useOnce(/* callback */);
client2.used; // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment