forked from Postman-Devrel/Banking-API-Demo
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdb.js
More file actions
58 lines (48 loc) · 1.41 KB
/
Copy pathdb.js
File metadata and controls
58 lines (48 loc) · 1.41 KB
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
/**
* In-memory store for books (demo only)
*/
const { v4: uuidv4 } = require('uuid');
const Book = require('../models/Book');
class Database {
constructor() {
this.books = new Map();
this._seed();
}
_seed() {
const sample = [
new Book('1', 'The Great Gatsby', 'F. Scott Fitzgerald', 1925, 'Scribner'),
new Book('2', '1984', 'George Orwell', 1949, 'Secker & Warburg')
];
sample.forEach(b => this.books.set(b.id, b));
}
getBooks() {
return Array.from(this.books.values());
}
getBookById(id) {
return this.books.get(id) || null;
}
createBook(data) {
const id = uuidv4().slice(0, 8);
const book = new Book(id, data.title.trim(), data.author.trim(), data.year ?? null, data.publisher ? data.publisher.trim() : null);
this.books.set(id, book);
return book;
}
updateBook(id, data) {
const book = this.books.get(id);
if (!book) return null;
if (data.title !== undefined) book.title = data.title.trim();
if (data.author !== undefined) book.author = data.author.trim();
if (data.year !== undefined) book.year = data.year;
if (data.publisher !== undefined) book.publisher = data.publisher ? data.publisher.trim() : null;
return book;
}
deleteBook(id) {
return this.books.delete(id);
}
/** Reset store and re-seed (for tests) */
reset() {
this.books.clear();
this._seed();
}
}
module.exports = new Database();