Created
April 5, 2021 20:45
-
-
Save jednano/058a9419934294f594a5c4b7382710ba to your computer and use it in GitHub Desktop.
Use Prisma Client Once
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
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