dimanche 15 septembre 2019

How to send a POST request with dynamic queryparam to Mirage?

I'm firing an action in a component to create a record with an argument(mediaType) in Mirage like so:

// my-component

actions: {
  submitForm() {
    let mediaType = 3;
    let item = this.store.createRecord('movie', { mediaType });

    return item.save(); // => POST to '/movies'
  }
}

Here is the movie model:

const { attr, Model } = DS;

export default Model.extend({
  mediaType: attr('number'),
  ...
});

In the adapter I use urlForCreateRecord to take mediaType property off of the model. I add it to the query string:

// adapters/my-component

namespace: '/theater',
CreateRecord(modelName, snapshot) {
  let rootURL = `${ENV.APP.apiEndpoint}/${this.namespace}`;
  let mediaType = snapshot.attr('mediaType');
  let data = this.serialize(snapshot);
  delete data.mediaType;

  return `${rootURL}/movies?mediaType=${mediaType}`; // => POST to '/theater/movies?mediaType=3'
}

And in Mirage I have the route set up like so:

// mirage/config.js

this.post('/theater/movies', ({ movie }, request) => {
  let { mediaType } = request.queryParams;
  let movieData = JSON.parse(request.requestBody);
  let returnArray = movieData.map((item) => {
    return movie.create(item);
  });

  return new Response(200, {}, returnArray);
});


But Mirage cannot find any route that matches this endpoint.

I've also hardcoded the endpoint like so but Mirage still couldn't find it:

// mirage/config.js

this.post('/theater/movies?mediaType=3', ({ movie }, request) => {
  ...
});

Any idea why Mirage throws there was no route defined to handle this request error?




Aucun commentaire:

Enregistrer un commentaire