Crea el proyecto Node.js
Tabla de contenidos
Inicializa el proyecto
Crea un nuevo proyecto Node.js:
$ npm init -y
Añade pg, jest y @testcontainers/postgresql como dependencias:
$ npm install pg --save
$ npm install jest @testcontainers/postgresql --save-dev
Implementa el repositorio de clientes
Crea src/customer-repository.js con funciones para gestionar clientes en PostgreSQL:
async function createCustomerTable(client) {
const sql =
"CREATE TABLE IF NOT EXISTS customers (id INT NOT NULL, name VARCHAR NOT NULL, PRIMARY KEY (id))";
await client.query(sql);
}
async function createCustomer(client, customer) {
const sql = "INSERT INTO customers (id, name) VALUES($1, $2)";
await client.query(sql, [customer.id, customer.name]);
}
async function getCustomers(client) {
const sql = "SELECT * FROM customers";
const result = await client.query(sql);
return result.rows;
}
module.exports = { createCustomerTable, createCustomer, getCustomers };El módulo proporciona tres funciones:
createCustomerTable()crea la tablacustomerssi no existe.createCustomer()inserta un registro de cliente.getCustomers()obtiene todos los registros de clientes.