-
Notifications
You must be signed in to change notification settings - Fork 0
/
adapter.ts
68 lines (63 loc) · 1.74 KB
/
adapter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { Pool } from "pg";
import format from "pg-format";
import { Repository } from "../types/dbAdapter";
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
export function pgAdapter<T>(tableName: string): Repository<T> {
return {
name: () => tableName,
create: async (data) => {
const result = await pool.query(
format(
`INSERT INTO %I (%I) VALUES (%L) RETURNING *`,
tableName,
Object.keys(data),
Object.values(data)
)
);
return result.rows[0];
},
readMany: async (filters) => {
const where = filters
.map((filter) => {
switch (filter.operator) {
case "=":
return `%I = %L`;
}
})
.join(" AND ");
const query = `SELECT * FROM ${tableName} ${
where ? `WHERE ${where}` : ""
}`;
const values = filters.flatMap((filter) => [filter.field, filter.value]);
const result = await pool.query(format(query, ...values));
return result.rows;
},
read: async (id) => {
const result = await pool.query(
`SELECT * FROM ${tableName} WHERE id = $1`,
[id]
);
return result.rows[0];
},
update: async (id, data) => {
const keys = Object.keys(data);
const result = await pool.query(
`UPDATE ${tableName} SET ${keys
.map((k, idx) => `${k} = $${idx + 2}`)
.join(", ")}
WHERE id = $1 RETURNING *`,
[id, ...Object.values(data)]
);
return result.rows[0];
},
delete: async (id) => {
const result = await pool.query(
`DELETE FROM ${tableName} WHERE id = $1 RETURNING *`,
[id]
);
return result.rows[0];
},
};
}