When you’re querying Postgres, you need to choose between:
If you want to use an ORM to query Postgres, I recommend using https://typeorm.io. If you’re starting with a fresh project, you can use their typeorm init
CLI command:
npx typeorm init --name MyProject --database postgrescd MyProject && yarn
You’ll then need to edit ormconfig.json
to add your database connection options. You’ll need to add a file in src/entity
for each table in your database.
You may also like: Restful API with NodeJS, Express, PostgreSQL, Sequelize, Travis, Mocha, Coveralls and Code Climate.
You can then use a JavaScript API to create records in your database:
import {createConnection} from "typeorm";
import {Photo} from "./entity/Photo";
async function createPhoto() {
const connection = await createConnection({
type: 'postgres',
url: process.env.DATABASE_URL || 'postgres://test:test@localhost/test'
});
const photo = new Photo();
photo.name = "Me and Bears";
photo.description = "I am near polar bears";
photo.filename = "photo-with-bears.jpg";
photo.views = 1;
photo.isPublished = true;
const {id} = await connection.manager.save(photo);
console.log("Photo has been saved. Photo id is", photo.id);}
createPhoto();
There are advantages to this approach (the biggest being that it supports strong types), but I personally feel that it makes the code pretty hard to read/follow, and the skills you learn on TypeORM will be of no use if you move to a different ORM
I believe that the simplest and easiest way to query Postgres is to directly write the SQL that will be run against your database.
“Using SQL directly, means there’s nothing to configure”
yarn add @databases/pg
You’ll need to set theDATABASE_URL
environment variable to a database connection string.
import connect, {sql} from '@databases/pg';
const db = connect();
export async function getAllUsers() {
return await db.query(sql`SELECT * FROM users;`);
}
export async function getUserById(userId) {
return (await db.query(sql`
SELECT * FROM users WHERE user_id=${userId}
`))[0];
}
export async function createUser(u) {
return (await db.query(sql`
INSERT INTO users (name, email)
VALUES (${u.name}, ${u.email})
RETURNING user_id;
`))[0].user_id;
}
export async function deleteUserById(userId) {
await db.query(sql`DELELTE FROM users WHERE user_id=${userId}`);
}
export async function updateUserById(userId, u) {
await db.query(sql`
UPDATE users
SET name=${u.name}, email=${u.email}
WHERE user_id=${userId}
`);
}
export async function upsertUser(userId, u) {
return (await db.query(sql`
INSERT INTO users (user_id, name, email)
VALUES (${userId}, ${u.name}, ${u.email})
ON CONFLICT (user_id)
DO UPDATE SET name=${u.name}, email={u.email}
RETURNING *;
`))[0];
}
N.B. The
[@databases](https://www.atdatabases.org/)
library does not just concatenate your user input into a string of SQL, it separates your parameters from the actual query, and uses prepared statements to run the query. It throws a clear runtime exception if you forget to tag your sql with thesql
tag. This means it’s virtually impossible for you to introduce SQL Injection vulnerabilities by accident.
For most projects, I recommend querying your Postgres database directly using @databases/pg
. It gives you the ultimate flexibility. If you need TypeScript types, I recommend declaring the types along with the SQL that queries. TypeScript isn’t currently able to check that the types match your database schema, but at least if they’re in the same file, you’ll probably remember to keep them in sync.
Thank for reading! If you liked this post, share it with all of your programming buddies!
#node-js #postgresql #sql #javascript #web-development