2,3ヶ月に1回調べては忘れるということがあったのでメモとして
この記事を書いたときのバージョン
{
"angular-in-memory-web-api": "^0.5.2"
}
シチュエーション
種別の検索条件(kind)付きのGETリクエストで記事一覧を取得したい
期待動作
全取得
リクエスト
api/articles?kind=
レスポンス
[
{
title: 'Test Page 01',
description: 'This is Test Page 01',
image: 'path/your/image.png',
kind: Kind.Sports
},
{
title: 'Test Page 02',
description: 'This is Test Page 02',
image: 'path/your/image.png',
kind: Kind.People
},
{
title: 'Test Page 03',
description: 'This is Test Page 03',
image: 'path/your/image.png',
kind: Kind.Technology
}
]
検索条件有り(kind=sports)
リクエスト
api/artiles?kind=sports
レスポンス
[
{
title: 'Test Page 01',
description: 'This is Test Page 01',
image: 'path/your/image.png',
kind: Kind.Sports
}
]
コード
実コードから引っ張ったので、一部無理やりAnyにしてます。
in-memory-data.service.ts
import {
InMemoryDbService,
RequestInfo,
RequestInfoUtilities,
ParsedRequestUrl,
ResponseOptions,
getStatusText,
STATUS
} from 'angular-in-memory-web-api';
enum Kind {
Sports = 'sports',
People = 'people',
Technology = 'technology'
}
const feed: Any[] = [
{
title: 'Test Page 01',
description: 'This is Test Page 01',
image: 'path/your/image.png',
kind: Kind.Sports
},
{
title: 'Test Page 02',
description: 'This is Test Page 02',
image: 'path/your/image.png',
kind: Kind.People
},
{
title: 'Test Page 03',
description: 'This is Test Page 03',
image: 'path/your/image.png',
kind: Kind.Technology
}
];
export class InMemoryDataService implements InMemoryDbService {
// オーバーライド
get(reqInfo: RequestInfo) {
const collectionName = reqInfo.collectionName;
if (collectionName === 'articles') {
return this.getArticles(reqInfo);
}
return undefined;
}
private getArticles(reqInfo: RequestInfo) {
return reqInfo.utils.createResponse$(() => {
console.log('HTTP GET override');
const collection = feed.slice();
const dataEncapsulation = reqInfo.utils.getConfig().dataEncapsulation;
const kind = reqInfo.query.get('kind');
const data = kind === undefined ? collection : this.filterFeed(kind[0]);
const options: any = data ?
{
body: dataEncapsulation ? { data } : data,
status: STATUS.OK
} :
{
body: { error: 'error' },
status: STATUS.NOT_FOUND
};
return this.finishOptions(options, reqInfo);
});
}
private finishOptions(options: ResponseOptions, { headers, url }: RequestInfo) {
options.statusText = getStatusText(options.status);
options.headers = headers;
options.url = url;
return options;
}
private filterFeed(kind: string) {
return feed.filter((value: FeedItem, index: number, array: FeedItem[]) => {
return (value.kind === kind);
});
}
createDb() {
return { feed };
}
}