CPNT 262 Day 18 - Query params and .filter()
Housekeeping
- Announced after lunch:
- Group assignments for Final Project
- Draft of Assignment 6 and Group Project announced
- Tooltime:
- Experiment: starter code in
in-class
- Syncing a Fork
- Experiment: starter code in
Trophy of the day
- A randy module: Build an express module that returns a random item from a List Entry endpoint.
- A filter that returns a list of poisoned guild members
1. Spoiler demo: Random array items
- Create a local module that accepts any array as an argument and returns a random item from that array. See: Find a random item in an Array
2. Query params
Materials
- Get Query Strings and Parameters in Express.js - Stack Abuse
- Gist: Handling URL query parameters
- REST APIs: Getting Started
Key Takeaways
- The
request
object stores parameters in three main objects:req.params
: Parameters passed as route segments.- Example:
GET /api/animals/:id
.
- Example:
req.query
: Parameters passed after the?
in a URL.- Example:
/api/animals?page=3&per_page=10
.
- Example:
req.body
: Parameters passed in the request body, such as when a form is submitted withmethod="POST"
.
- Query parameters are not included in the path when being matched by
app.get()
and the other method handlers. - In REST APIs, query parameters are most used for:
- filtering
- sorting
- pagination
- search
- Query params are usually applied to a List Entry endpoint, even if only one item is returned.
Demo: Random guild member endpoint
Find a random guild member using this sample code:Find a random item in an Array
- Starter Code
Activity
Build your own local module that returns a random item in an array and apply it to your own List Entry route (i.e. from Assignment 5).
3. Filtering arrays with Array.filter()
Materials
Key Takeaways
Array.filter()
loops through an array of objects, expects a Boolean return value and it creates a new empty array that will be returned at the end of the loop:- If
true
is returned, the current item is added to the new array; - If
false
is returned, the loop continues to the next item; - At the end of the loop,
Array.find()
returns the new array containing all the items that passed the test.
- If
- The
.filter()
method operates very similarly to.find()
, except that it returns an array instead of a single item. .filter()
returns a new array, it does not modify the original array.
Activity
Modify the List Entry endpoint of the Guild sample code so that it can return a list of poisoned guild members.
Lab Time
- Final Project: Group assignments
- Decide on a group name
- Decide on a theme for your website
- Morning Activities
- Stretch resources:
- REST API: Sorting, Filtering, and Pagination by Tania Rascia
- Sort an Array of Objects in JavaScript
- Reference:
Array.prototype.sort()
- Reference: