boredProjects
boredProjects

Reputation: 343

Querying my Cloud Sql DB from my Node.js backend

Recently I've been learning google cloud sql it took a little but I was able to connect my cloud sql auth proxy to my postgres client. However I'm not sure how to query or make post request to my cloud sql. Originally I was just doing

const Pool = require("pg").Pool;

const pool = new Pool({
    user: "postgres",
    password: "****",
    host: "localhost",
    port: 5432,
    database: "somedb"
});

I'm not sure how to convert this over to try and query the cloud sql db. I did try converting it and got.

const Pool = require("pg").Pool;

const pool = new Pool({
    user: "postgres",
    password: "****",
    host: "[cloud sql ip]",
    port: 5432,
    database: "[pg/gc db]"
});

I end up getting the error [pg_hba.conf rejects connection for host "[ipv4 ip]", user "postgres", database "[pg/gc db]", no encryption]. I know that the documentation has a code sample but I don't understand it and cant really find any resources on explaining it.

Edit: I am uploading files to a bucket in cloud storage which I was successfully able to do. I plan on mapping out all these files onto a webpage. However I would like to filter them by certain features so I am making a second request after I store the file. My second request will store attributes into a database that I can then relate to the files for filtering.

Upvotes: 0

Views: 407

Answers (1)

Gabe Weiss
Gabe Weiss

Reputation: 3342

If you're running the auth proxy from your local machine where you're running your application, then the code will be the same from your application's code perspective. You'll still connect to localhost (although you may need to connect to 127.0.0.1 depending on how you have hosts set up on the machine).

The database field will depend on how you've set up the database in Cloud SQL, but it should be the same as your local database. E.g. if you created a database named "somedb" in Cloud SQL, you don't have to change anything to connect to it in Cloud SQL. The proxy running locally will make everything behave as if you're running the database locally from the application's perspective.

Edit: This particular answer wasn't the issue they were having, but in the comments it came up that both the Proxy and SSL-only was being used, which is (generally) less recommended as it doubles up the SSL/TLS usage because the Proxy also uses generated SSL certificates to connect to Cloud SQL so the database-level SSL connectivity is a redundancy that's likely not needed. There are some edge cases where you may want both, but broadly speaking one or the other is recommended.

Upvotes: 1

Related Questions