Exercise: Pet API Warm-Up
Finish the three async functions in the pet adoption API's data file, listing pets by species, finding one pet by its id and adding a pet, so its routes work, and let the Supertest tests check every answer.
Apprentice · JavaScript · Node.js · REST API · Updated
The Maple Street Pet Adoption Center's API runs, but its data file isn't finished: asking for the cats brings back every pet, Mochi can't be found by her id, and adding a new dog stops with an error. You'll finish the three functions in data/pets.js that the routes call, in the JavaScript from this chapter. Tests send real requests to the API and check every answer. This is also your warm-up for the next chapter, which keeps these routes and moves the pets into MongoDB.
Get the exercise code
This lesson's GitHub repository is github.com/ask-codey/exercise-mongodb-pet-api-warm-up, also linked from the Exercise box beside the lesson. If you cloned it in A Tour of the Express Starter: Routes, Requests and Responses, open that folder in VS Code and skip to What to do. If not, clone it into your mongodb-course folder. In VS Code's terminal:
cd ~/mongodb-course
git clone https://github.com/ask-codey/exercise-mongodb-pet-api-warm-up.git
Git makes a folder, exercise-mongodb-pet-api-warm-up, with the exercise code inside. Open that folder in VS Code (File > Open Folder), open its terminal, and install Express and the package the tests use:
npm install
The folder holds:
data/pets.js: the center's six pets and the three functions you'll finish.routes/pets.js,app.js,problems.jsandserver.js: the rest of the API, ready to use. The tour explains each one.pets.http: the requests to try with REST Client.test/app.test.js: the tests. You don't need to change it.
What to do
Open data/pets.js. Every pet in it is an object, { id, name, species, age, traits, status }, and its id is text, such as "2". The six pets are Biscuit ("1", a dog), Mochi ("2", a cat), Pepper ("3", a dog), Clover ("4", a rabbit), Juniper ("5", a cat who's been adopted) and Rocket ("6", a dog). The comment above each function says what it should give back, with examples:
/*
* 2. Give back the pet whose id is id, or null when no pet has that id.
*
* id is the text from the address, such as "2" from /pets/2.
*
* getPet("2") -> Mochi's whole pet object: { id: "2", name: "Mochi", species: "cat", age: 2, ... }
* getPet("99") -> null
*
* For now it never finds a pet.
*/
export async function getPet(id) {
return null;
}
Replace the body of each function with your own code:
listPets(species): the pets whosespeciesisspecies, in the order they're kept, or every pet whenspeciesisundefined(the address has no?species=).listPets("cat")gives back Mochi and Juniper;listPets("parrot")gives back an empty list,[].getPet(id): the pet whoseidisid, ornullwhen there's none.getPet("2")gives back Mochi;getPet("99")gives backnull, and the route turns that into a 404.addPet(pet):petis{ name, species, age, traits }from the request's body. Save a new pet with those four fields, plus anid, which isnextIdas text ("7"for the first new pet), and thestatus"available". Add 1 tonextId, put the new pet at the end ofpets, and give it back.
For example, POST /pets with the body { "name": "Waffles", "species": "dog", "age": 4, "traits": ["good with kids"] } answers 201 with exactly:
{"id":"7","name":"Waffles","species":"dog","age":4,"traits":["good with kids"],"status":"available"}
Check your work
Run the tests from the exercise folder:
npm test
No server needs to be running: each test hands a request straight to createApp(), and puts the six pets back before it starts. At first, 6 of the 8 tests fail; that's expected. The other two, GET /pets with every pet and GET /pets/99 with a 404, already pass because the starter's placeholders happen to get them right, and they must still pass when you're done. A failing test's message says what it expected and what came back, for example listPets("cat") should give back only the cats. Juniper is adopted, and still a cat. It gave back ["Biscuit","Mochi","Pepper","Clover","Juniper","Rocket"].
To try the API yourself, start it with npm start (or npm run dev, which restarts it each time you save), then use your browser and pets.http. Stop it with Ctrl+C. Every restart starts again from the same six pets, because they're kept in memory.
Hints
- One list method for each job. The JavaScript You Need: Variables, Functions and Modules shows the two that do most of the work here:
filterkeeps every pet your arrow function says yes to, andfindgives back the first one, orundefined. - Check for a missing value first. With no
?species=,speciesisundefined: return every pet before you filter.findgivesundefinedwhen no pet matches, andgetPetmust give backnullinstead. - Compare text with text.
idarrives as text, such as"2", and every pet'sidis text too, so===compares them as they are. nextIdis a number. A template literal,`${nextId}`, turns it into text. Add 1 to it after you use it, as the counter does in the lesson.pushputs a pet at the end of a list, solistPetsandgetPetfind it from then on.
When you're done
Every test is green, and npm test prints:
✔ 1) GET /pets answers 200 with all 6 pets, Biscuit to Rocket (30.8633ms)
✔ 2) GET /pets?species=cat answers 200 with the 2 cats, Mochi and Juniper (5.5478ms)
✔ 3) GET /pets?species=dog answers 200 with the 3 dogs, Biscuit, Pepper and Rocket (3.9613ms)
✔ 4) GET /pets?species=parrot answers 200 with an empty list, [] (3.9669ms)
✔ 5) GET /pets/2 answers 200 with Mochi (4.3781ms)
✔ 6) GET /pets/99 answers 404 with "There's no pet 99." (4.499ms)
✔ 7) POST /pets with Waffles answers 201 with Waffles, id "7" and status "available" (12.2313ms)
✔ 8) after POST /pets with Waffles, GET /pets/7 answers 200 with Waffles and GET /pets lists 7 pets (11.5091ms)
ℹ tests 8
ℹ suites 0
ℹ pass 8
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 306.7852
The times in parentheses will be different on your computer. With npm start running, http://localhost:3100/pets?species=cat now shows only Mochi and Juniper. Now look at routes/pets.js: you didn't change a line of it, and every route works. What would have to change in it if the pets lived in a database instead of an array?
Submit your exercise
The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.
On GitHub, click +, then New repository. Name it (for example
exercise-mongodb-pet-api-warm-up), choose Public, and click Create repository. Leave out the README: your folder already has one.In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:
git remote set-url origin https://github.com/your-name/exercise-mongodb-pet-api-warm-up.git git add . git commit -m "My solution" git push -u origin mainPaste your repo's address, such as
https://github.com/your-name/exercise-mongodb-pet-api-warm-up, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.
Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.
So what
The routes ask, the data file answers, and the tests prove every answer: that split is what lets the next chapter swap an array for MongoDB without touching a single route.