I am playing around with angular-in-memory-web-api for Angular 2. So far I have only been using GET calls and it's working well.
The API I'm going to call is only using POST calls so I began rewriting my GET calls to POST calls, but then they stopped returning the mock data. In my test function bellow, I want to get the data as a TestResponse object by an id:
postTest(id: string): Promise<TestResponse> {
return this.http
.post(this.testUrl, JSON.stringify({ testId: id }), { headers: this.headers })
.toPromise()
.then(response => response.json().data as TestResponse)
.catch(this.handleError);
}
And the mock data:
let test = [
{ testId: 'e0d05d2b-3ec3-42ae-93bc-9937a665c4d6', missingData: 'qwerty', moreMissingData: 'asdfgh' },
{ testId: 'dccef969-b9cf-410a-9973-77549ec47777', missingData: 'qwerty', moreMissingData: 'asdfgh' },
{ testId: '20716fd7-1f50-4a12-af16-52c009bc42ab', missingData: 'qwerty', moreMissingData: 'asdfgh' }
];
If I understand this right, this code will assume that I want to create something and is therefor bouncing my testId back together with id: 1 (which doesn't even follow my data structure).
So, my question is, how can I get my mock data with POST calls?
It is possible to override HTTP methods in your in memory data service implementation.
In the overridden method (e.g POST), it is possible to react to the collection name (via the RequestInfo
parameter) to provide specific functionality on a per-endpoint/collection basis.
A provided example deals with GET calls only: https://github.com/angular/in-memory-web-api/blob/master/src/app/hero-in-mem-data-override.service.ts
From that, overriding the POST functionality could look like this:
import { InMemoryDbService, RequestInfo, STATUS, ResponseOptions } from 'angular-in-memory-web-api';
export class Your InMemoryDataService implements InMemoryDbService {
// ...
post(requestInfo: RequestInfo) {
const collectionName = requestInfo.collectionName;
if (collectionName === 'somedatatype') {
// Intercept POST calls to the 'somedatatype' collection:
// E.g. add some fields to our entity that would be set in the backend,
const data = requestInfo.utils.getJsonBody(requestInfo.req);
const collection = requestInfo.collection;
data.extraField = 'hello';
// set id to next highest number
data.id = collection.map(item => item.id).reduce((cur, next) => cur > next ? cur : next) + 1;
// ... add the item to the collection
collection.push(data);
// forge the response
const options: ResponseOptions = {
body: { data },
status: STATUS.OK,
headers: requestInfo.headers,
url: requestInfo.url
};
// use createResponse$ to return proper response
return requestInfo.utils.createResponse$(() => options);
}
// let the default POST handle all other collections by returning undefined
return undefined;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With