Skip to main content

Making an Endpoint

Implementing the endpoint

Endpoints consist of:

  • an endpoint function: this is a javascript function of the form f(req, res), where req and res are express Request and Response objects. It lives in api > endpointsFunctions > ..., and implements whatever functionality we want from the endpoint, e.g. getting a story by id.
  • a route: this is a URI string that identifies the endpoint. It lives in api > routes > *.route.js. We point specify the route using the makeEndpoints() function. See an example of this being used in the story routes file.

In order to make a new endpoint, first implement the endpoint function, and then specify it's route in the appropriate .route.js file. The route files correspond to the models that their endpoints operate on.

The easiest way to go about this is to copy and edit an existing endpoint. You'll want to find the existing endpoint that is most similar to the one you want to implement.

Here's a PR that traces the entire process of adding a new endpoint + tests: https://github.com/OisinNolan/An-Scealai/pull/173/files.

Testing

We currently have two ways to test our endpoints:

  • function-level tests: these can be used to test that the endpoint function logic is working correctly. We can use mock requests and mock responses to provide the possible input cases to the endpoint function, and ensure that they return the appropriate response, or throw the expected error. We use mockingoose to mock responses from mongoose functions like .find() and .update(). These tests live alongside endpoint functions in api > endpointsFunctions > * > *.test.js. An example is getStoryById.test.js.
  • end-to-end tests: these are for testing routes end-to-end. For each test we make a fresh database which we populate with real documents to check that our endpoints work on an API level. We can check for a number of cases that the response status and body contain what we expect them to. We use supertest to mock the requests. These live alongside route files in api > routes > *.route.test.js. An example is story.route.test.js.

To run tests use npm test in the /api directory.