Adding an API endpoint for saving data
In this section, we’ll start by adding the POST
request handler function for saving data and then continue with the PUT
function, in its own route file, for updating data.
Let’s begin with a test helper:
- Create a new file,
src/factories/request.js
, with the following content. This will be used by both thePOST
andPUT
functions to read the data of the request. SvelteKit will pass aRequest
argument. The only bit of this we need to provide is thejson
method, as shown here:export const createRequest = (json) => ({ json: () => Promise.resolve(json) });
Providing minimal versions of collaborating objects
SvelteKit passes the Request
objects into our request handler functions. But for our unit tests we don’t need fully formed Request
objects, we just need an object that implements the parts of the interface that we use. Our application code doesn’t use anything but the json
method...