A Data Layer
A Data Layer: A Data Layer: One File That Talks to the Database, When the Database Says No: Bad ids, Duplicates and Not Found, Testing the Data Layer with…
Updated
- A Data Layer: One File That Talks to the Database (Journeyman): A data layer keeps every driver call in one file, data/pets.js, whose functions listPets, getPet, addPet and updatePet the routes call without ever touching the driver, turning each document into a plain pet and building filters, a projection, a sort and pages from the query string.
- When the Database Says No: Bad ids, Duplicates and Not Found (Journeyman): An API answers each way a request can fail with the status that says whose problem it is, so a text that isn't an ObjectId gets 400, an id with no pet 404, a duplicate key (code 11000) 409, a document the validator refuses (code 121) 400, and a database that's down 500 with the details logged and never sent.
- Testing the Data Layer with mongodb-memory-server (Journeyman): mongodb-memory-server starts a real, throwaway MongoDB for a test file, the way the helper in every exercise of this course does, so before starts it, beforeEach puts the same documents back for every test, node --test and assert check the data layer, Supertest checks a route, and after stops it, never touching your own data.