Implement a repository with a database and a fake
Implement a repository with a database and a fake in JavaScript: two classes, one interface, a test that needs no SQL. Node.js 24.
Services should not know whether a user comes from SQLite or an array. A repository hides that, and a fake with the same methods stands in during tests.
import { DatabaseSync } from 'node:sqlite';
class SqliteUserRepository {
constructor(db) {
this.db = db;
db.exec('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)');
}
add(name) {
return Number(this.db.prepare('INSERT INTO users (name) VALUES (?)').run(name).lastInsertRowid);
}
find(id) {
return this.db.prepare('SELECT id, name FROM users WHERE id = ?').get(id) ?? null;
}
}
class FakeUserRepository {
#rows = [];
add(name) {
this.#rows.push({ id: this.#rows.length + 1, name });
return this.#rows.length;
}
find(id) {
return this.#rows.find((row) => row.id === id) ?? null;
}
}
for (const repo of [new SqliteUserRepository(new DatabaseSync(':memory:')), new FakeUserRepository()]) {
const id = repo.add('Ada');
console.log(id, repo.find(id).name, repo.find(99));
}1 Ada null
1 Ada nullBoth classes give the same answers to add and find, so code that takes a repository runs unchanged against either. The loop is also a handy contract test: run the same checks on every implementation.
SQLite's rows come back as objects with a null prototype, so compare fields and not whole objects when you assert. node:sqlite is built into Node.js 24.