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:

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


2. Query params

Materials

Key Takeaways

  • The request object stores parameters in three main objects:
    1. req.params: Parameters passed as route segments.
      • Example: GET /api/animals/:id.
    2. req.query: Parameters passed after the ? in a URL.
      • Example: /api/animals?page=3&per_page=10.
    3. req.body: Parameters passed in the request body, such as when a form is submitted with method="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

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.
  • 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