Skip to content

Make Prisma examples more production friendly #416

@jackwotherspoon

Description

@jackwotherspoon

Today our Prisma examples have a single connect() function that creates a Connector,
starts a local proxy listener, and then creates a PrismaClient.

It returns the PrismaClient, and a function to close the client and Connector for the user
to call when done with database connections.

While this example works, it is not production friendly.

Ideally all connections to a single Cloud SQL instance should share a Connector and the
local proxy, not create a new one for each database user.

export async function connect({instanceConnectionName, user, database}) {
const path = resolve('.s.PGSQL.5432'); // postgres-required socket filename
const connector = new Connector();
await connector.startLocalProxy({
instanceConnectionName,
ipType: IpAddressTypes.PUBLIC,
authType: AuthTypes.IAM,
listenOptions: {path},
});
// note that the host parameter needs to point to the parent folder of
// the socket provided in the `path` Connector option, in this example
// that is going to be the current working directory
const datasourceUrl = `postgresql://${user}@localhost/${database}?host=${process.cwd()}`;
const prisma = new PrismaClient({datasourceUrl});
// Return PrismaClient and close() function. Call close() when you are
// done using the PrismaClient to ensure client gracefully disconnects and
// local Unix socket file created by the Connector is deleted.
return {
prisma,
async close() {
await prisma.$disconnect();
connector.close();

Solution is to move the Connector initialization and connector.startLocalProxy call out of connect(), so that the Connector can be shared across multiple connect invocations and across PrismaClients for different users.

Related to #345

Metadata

Metadata

Labels

priority: p2Moderately-important priority. Fix may not be included in next release.type: docsImprovement to the documentation for an API.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions