Created
January 26, 2021 13:45
-
-
Save glauber-sampaio/f5b449604b2893df62dba33b653d496a to your computer and use it in GitHub Desktop.
Inspired by Supabase way of querying database, using a simple JavaScript method chaining.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// node-postgres | |
const { Pool } = require('pg') | |
// Connection String | |
const config = { | |
connectionString: (process.env.NODE_ENV === 'production') ? process.env.DATABASE_URL : 'postgres://me:password@localhost:5432/database_name' | |
} | |
/* | |
==================================== | |
Query helper | |
==================================== | |
How to use: | |
const query = new Query() | |
const resultA = await query.select().from('countries').where({ currency: 'USD' }).go() | |
const resultB = await query.select('id, name, email').from('users').go() | |
const resultC = await query | |
.select() | |
.from('posts') | |
.where( | |
{ | |
published: true, | |
author: 'glauber' | |
} | |
) | |
.go() | |
==================================== | |
The output result will be the database query result, | |
which can be an Array of objects or a simple Object. | |
I wish I could remove the go() at the end, but right now | |
not sure how to do it. I hope you like it and feel free | |
to contribute. | |
==================================== | |
*/ | |
export class Query { | |
constructor() { | |
this.text = '' | |
this.values = [] | |
} | |
select(q) { | |
this.text = q == undefined ? 'SELECT *' : `SELECT ${q}` | |
return this | |
} | |
from(q) { | |
if (q === undefined) throw new Error('~FROM está vazio.') | |
this.text += ` FROM ${q}` | |
return this | |
} | |
where(q) { | |
const { length } = Object.keys(q) | |
let sentence = '' | |
this.values = [] | |
Object.entries(q).forEach(([k, v], i) => { | |
const index = (i + 1) | |
const match = `${k} = $${index}` | |
this.values.push(v) | |
sentence += `${match}` | |
if (length > 1 && index < length) { | |
sentence += ', ' | |
} | |
}) | |
this.text += ` WHERE ${sentence}` | |
return this | |
} | |
orderBy(q) { | |
if (q === undefined) throw new Error('~ORDER BY está vazio.') | |
this.text += ` ORDER BY ${q}` | |
return this | |
} | |
async go() { | |
return new Promise(async (resolve, reject) => { | |
const pool = new Pool(config) | |
try { | |
const { rows } = await pool.query(this.text, this.values) | |
if (rows.length === 1) { | |
resolve(rows[0]) | |
} else { | |
resolve(rows) | |
} | |
pool.end() | |
} | |
catch (e) { reject(e) } | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment