-
Notifications
You must be signed in to change notification settings - Fork 13
Description
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.
cloud-sql-nodejs-connector/examples/prisma/postgresql/connect.ts
Lines 23 to 46 in 6040826
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