planetscale-node icon indicating copy to clipboard operation
planetscale-node copied to clipboard

URL builder

Open chrbala opened this issue 4 years ago • 2 comments

I just connected PlanetScale with Prisma and Vercel and there was a bit more friction than I think was necessary. I started with the Vercel integration, which added some env variables. It wasn't clear how I was expected to connect, but I ended up doing it initially with a single DB_URL env variable, and ultimately made a URL builder function.

It seems like this setup should be easier. I'm not sure exactly the best way, but perhaps one way could be by exposing a simple URL builder function in this package.

My implementation is as follows:

const dbUrl = () => {
  const user = process.env.PLANETSCALE_DB_USERNAME;
  const password = process.env.PLANETSCALE_DB_PASSWORD;
  const db = process.env.PLANETSCALE_DB;
  const host = process.env.PLANETSCALE_DB_HOST;
  const certPath = process.env.PLANETSCALE_SSL_CERT_PATH;

  const hasAllValues =
    [user, password, db, host, certPath].findIndex(value => !value) === -1;
  if (!hasAllValues) return null;

  return `mysql://${user}:${password}@${host}/${db}?sslmode=require&sslcert=${certPath}`;
};

chrbala avatar Jan 12 '22 07:01 chrbala

If you are still using Prisma, you could use the .env file to construct the final connection string in there: https://www.prisma.io/docs/guides/development-environment/environment-variables#expanding-variables

Would probably look like this:

DATABASE_URL=mysql://${PLANETSCALE_DB_USERNAME}:${PLANETSCALE_DB_PASSWORD}@${PLANETSCALE_DB_HOST}/${PLANETSCALE_DB}?sslmode=require&sslcert=${PLANETSCALE_SSL_CERT_PATH}

Let me know if this actually works, and we can make a note to add that to some PlanetScale + Vercel documentation maybe.

janpio avatar Jan 12 '22 12:01 janpio

That solution ended up not working for me, I believe because I am running my code in an AWS Lambda which does not have my env file available. I ended up including the whole string as a separate env variable in Vercel.

chrbala avatar Jan 20 '22 09:01 chrbala