Skip to content

Commit b72d950

Browse files
committed
docs: update README for v2
1 parent b230f6c commit b72d950

File tree

2 files changed

+124
-88
lines changed

2 files changed

+124
-88
lines changed

README.ja.md

Lines changed: 62 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
MSW を型安全に使うための、aspida ユーザー向けのラッパー
44

5-
- Simple.
6-
- Type safe.
7-
- Aspida-like interface.
5+
- Simple
6+
- Type safe
7+
- Aspida-like interface
88

99
[English](./README.md) / [日本語](./README.ja.md)
1010

@@ -17,52 +17,62 @@ npm install mswpida --save-dev
1717
## 使い方
1818

1919
```ts
20-
import { createTypedRest } from 'mswpida';
20+
// 1. aspida で生成した `api` 関数から `typedHttp` を作る
21+
22+
import { createTypedHttp } from 'mswpida';
2123
import api from './awesome/store/$api';
2224

23-
// 1. aspida で生成した `api` 関数から `typedRest` を作る
24-
const typedRest = createTypedRest(api);
25+
const typedHttp = createTypedHttp(api);
26+
27+
// 2. `typedHttp` を使って MSW の request handler を書く
28+
29+
import { HttpResponse } from 'msw';
2530

26-
// 2. `typedRest` を使って MSW の request handler を書く
2731
const handlers = [
28-
typedRest.products._productId.images.$post((req, res, ctx) => {
29-
console.log(`Add an image to product ${req.params.productId}`); // パスパラメータに型がついている ✅
30-
console.log(`Image description: ${req.body.description}`); // リクエストボディに型がついている ✅
31-
return res(
32-
ctx.status(201),
33-
ctx.json({ id: 123, ...req.body }), // レスポンスボディにも型がついている ✅
32+
typedHttp.products._productId.images.$post(({ request, params }) => {
33+
console.log(`Add an image to product ${params.productId}`); // パスパラメータに型がついている ✅
34+
35+
const reqBody = await request.json();
36+
console.log(`Image description: ${reqBody.description}`); // リクエストボディに型がついている ✅
37+
38+
return HttpResponse.json(
39+
{ id: 123, ...reqBody }, // レスポンスボディにも型がついている ✅
40+
{ status: 201 },
3441
);
3542
}),
3643
// ...
3744
];
3845

3946
// 3. 以降は通常の MSW の使い方と同様
40-
import { setupWorker } from 'msw'; // or `setupServer`
47+
48+
import { setupWorker } from 'msw/browser';
49+
// or
50+
// import { setupServer } from 'msw/node';
4151

4252
await setupWorker(...handlers).start();
4353
```
4454

45-
### `createTypedRest(api, options?)`
55+
### `createTypedHttp(api, options?)`
4656

47-
aspida で生成した `api` 関数を元にして、`typedRest` というオブジェクトを作成します。この `typedRest` は、MSW の [request handler](https://v1.mswjs.io/docs/basics/request-handler) を書くためのラッパーです。
57+
aspida で生成した `api` 関数を元にして、`typedHttp` というオブジェクトを作成します。この `typedHttp` は、MSW の [request handler](https://mswjs.io/docs/concepts/request-handler) を書くためのラッパーです。
4858

4959
#### オプション
5060

5161
- `baseURL` (optional): API のベース URL を指定します。aspida の `baseURL` オプションと同様です。
5262

5363
```ts
54-
createTypedRest(api, { baseURL: 'https://staging.example.com' });
64+
createTypedHttp(api, { baseURL: 'https://staging.example.com' });
5565
```
5666

57-
### `typedRest`
67+
### `typedHttp`
5868

59-
MSW の [request handler](https://v1.mswjs.io/docs/basics/request-handler) を書くためのオブジェクトで、実態としては MSW の [`rest`](https://v1.mswjs.io/docs/api/rest) の薄いラッパーです。[`rest`](https://v1.mswjs.io/docs/api/rest) とほぼ同じ使い方ですが、パスやメソッドは aspida のような形式で表現します。
69+
MSW の [request handler](https://mswjs.io/docs/concepts/request-handler) を書くためのオブジェクトで、実態としては MSW の [`http`](https://mswjs.io/docs/api/http) の薄いラッパーです。使い方は `http` とほぼ同じですが、パスやメソッドは aspida のような形式で表現します。
6070

6171
```ts
62-
const handler = typedRest.products._productId.images.$post((req, res, ctx) => ...);
72+
const handler = typedHttp.products._productId.images.$post(({ request, params }) => ...);
6373

6474
// これは以下と同等
65-
const handler = rest.post('https://example.com/products/:productId/images', (req, res, ctx) => ...);
75+
const handler = http.post('https://example.com/products/:productId/images', ({ request, params }) => ...);
6676
```
6777

6878
#### パス
@@ -72,36 +82,36 @@ const handler = rest.post('https://example.com/products/:productId/images', (req
7282
`.$path()` を使うと、そのエンドポイントのパスを文字列として取得できます。
7383

7484
```ts
75-
const path = typedRest.products._productId.images.$path();
85+
const path = typedHttp.products._productId.images.$path();
7686
// -> 'https://example.com/products/:productId/images'
7787
```
7888

7989
#### メソッド
8090

81-
`.$get(resolver)``.$post(resolver)` など、HTTP メソッドに `$` を付けた関数で表現します。引数は MSW の [response resolver](https://v1.mswjs.io/docs/basics/response-resolver) ですが、aspida の `api` から導出した具体的な型が以下の3つについているため、型注釈を書く必要はありません。
91+
`.$get(resolver)``.$post(resolver)` など、HTTP メソッドに `$` を付けた関数で表現します。引数は MSW の [response resolver](https://mswjs.io/docs/concepts/response-resolver) ですが、aspida の `api` から導出した具体的な型が以下の3つについているため、型注釈を書く必要はありません。
8292

83-
- パスパラメータ `req.params`
93+
- パスパラメータ[`params`](https://mswjs.io/docs/network-behavior/rest#reading-path-parameters)
8494
- MSW の仕様上、値の型は常に `string` になります。
85-
- リクエストボディ `req.body`
86-
- ただし `await req.json()` の方には型はつかず、[常に `any` になります](https://github.com/mswjs/msw/issues/1318#issuecomment-1205149710)
87-
- レスポンスボディ `res(ctx.json())`
95+
- リクエストボディ:[`await request.json()`](https://mswjs.io/docs/network-behavior/rest#reading-request-body)
96+
- レスポンスボディ:[`HttpResponse.json()`](https://mswjs.io/docs/api/http-response#httpresponsejsonbody-init) の第1引数
8897

8998
```ts
90-
const handler = typedRest.products._productId.images.$post((req, res, ctx) => {
91-
console.log(`Add an image to product ${req.params.productId}`); // パスパラメータに型がついている ✅
92-
console.log(`Image description: ${req.body.description}`); // リクエストボディに型がついている ✅
93-
return res(
94-
ctx.status(201),
95-
ctx.json({ id: 123, ...req.body }), // レスポンスボディにも型がついている ✅
96-
);
97-
});
98-
```
99+
const handler = typedHttp.products._productId.images.$post(
100+
({ request, params }) => {
101+
console.log(`Add an image to product ${params.productId}`); // パスパラメータに型がついている ✅
99102

100-
## FAQ
103+
const reqBody = await request.json();
104+
console.log(`Image description: ${reqBody.description}`); // リクエストボディに型がついている ✅
101105

102-
### MSW 2.x には対応していますか?
106+
return HttpResponse.json(
107+
{ id: 123, ...reqBody }, // レスポンスボディにも型がついている ✅
108+
{ status: 201 },
109+
);
110+
},
111+
);
112+
```
103113

104-
まだ対応していませんが、[対応予定です](https://github.com/mashabow/mswpida/issues/13)
114+
## FAQ
105115

106116
### エラーレスポンスなど、正常系以外のレスポンスボディを返そうとすると型エラーになります。
107117

@@ -110,16 +120,24 @@ const handler = typedRest.products._productId.images.$post((req, res, ctx) => {
110120
```ts
111121
type ErrorResponseBody = { errorCode: string };
112122

113-
const handler = typedRest.products._productId.images.$post<ErrorResponseBody>(
114-
(req, res, ctx) => {
115-
if (req.params.productId === 'bad_id') {
116-
return res(ctx.status(404), ctx.json({ errorCode: 'product_not_found' }));
123+
const handler = typedHttp.products._productId.images.$post<ErrorResponseBody>(
124+
({ request, params }) => {
125+
if (params.productId === 'bad_id') {
126+
return HttpResponse.json(
127+
{ errorCode: 'product_not_found' },
128+
{ status: 404 },
129+
);
117130
}
118-
return res(ctx.status(201), ctx.json({ id: 123, ...req.body }));
131+
const reqBody = await request.json();
132+
return HttpResponse.json({ id: 123, ...reqBody }, { status: 201 });
119133
},
120134
);
121135
```
122136

137+
### MSW v1 と一緒に使えますか?
138+
139+
mswpida v1 を使ってください。
140+
123141
## ライセンス
124142

125143
MIT

README.md

Lines changed: 62 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
A wrapper to use MSW in a type-safe manner for aspida users.
44

5-
- Simple.
6-
- Type safe.
7-
- Aspida-like interface.
5+
- Simple
6+
- Type safe
7+
- Aspida-like interface
88

99
[English](./README.md) / [日本語](./README.ja.md)
1010

@@ -17,52 +17,62 @@ npm install mswpida --save-dev
1717
## Usage
1818

1919
```ts
20-
import { createTypedRest } from 'mswpida';
20+
// 1. Create `typedHttp` from the `api` function generated by aspida.
21+
22+
import { createTypedHttp } from 'mswpida';
2123
import api from './awesome/store/$api';
2224

23-
// 1. Create `typedRest` from the `api` function generated by aspida.
24-
const typedRest = createTypedRest(api);
25+
const typedHttp = createTypedHttp(api);
26+
27+
// 2. Write MSW's request handler using `typedHttp`.
28+
29+
import { HttpResponse } from 'msw';
2530

26-
// 2. Write MSW's request handler using `typedRest`.
2731
const handlers = [
28-
typedRest.products._productId.images.$post((req, res, ctx) => {
29-
console.log(`Add an image to product ${req.params.productId}`); // Path parameter is typed ✅
30-
console.log(`Image description: ${req.body.description}`); // Request body is typed ✅
31-
return res(
32-
ctx.status(201),
33-
ctx.json({ id: 123, ...req.body }), // Response body is also typed ✅
32+
typedHttp.products._productId.images.$post(({ request, params }) => {
33+
console.log(`Add an image to product ${params.productId}`); // Path parameter is typed ✅
34+
35+
const reqBody = await request.json();
36+
console.log(`Image description: ${reqBody.description}`); // Request body is typed ✅
37+
38+
return HttpResponse.json(
39+
{ id: 123, ...reqBody }, // Response body is also typed ✅
40+
{ status: 201 },
3441
);
3542
}),
3643
// ...
3744
];
3845

3946
// 3. Subsequent usage is the same as the regular MSW usage.
40-
import { setupWorker } from 'msw'; // or `setupServer`
47+
48+
import { setupWorker } from 'msw/browser';
49+
// or
50+
// import { setupServer } from 'msw/node';
4151

4252
await setupWorker(...handlers).start();
4353
```
4454

45-
### `createTypedRest(api, options?)`
55+
### `createTypedHttp(api, options?)`
4656

47-
Creates a `typedRest` object based on the `api` function generated by aspida. This `typedRest` is a wrapper to write MSW's [request handler](https://v1.mswjs.io/docs/basics/request-handler).
57+
Creates a `typedHttp` object based on the `api` function generated by aspida. This `typedHttp` is a wrapper to write MSW's [request handler](https://mswjs.io/docs/concepts/request-handler).
4858

4959
#### Options
5060

5161
- `baseURL` (optional): Specifies the base URL for the API. Works the same as aspida's `baseURL` option.
5262

5363
```ts
54-
createTypedRest(api, { baseURL: 'https://staging.example.com' });
64+
createTypedHttp(api, { baseURL: 'https://staging.example.com' });
5565
```
5666

57-
### `typedRest`
67+
### `typedHttp`
5868

59-
An object for writing MSW's [request handler](https://v1.mswjs.io/docs/basics/request-handler). Essentially, it is a thin wrapper for MSW's [`rest`](https://v1.mswjs.io/docs/api/rest). The usage is almost identical to [`rest`](https://v1.mswjs.io/docs/api/rest), but paths and methods are expressed in an aspida-like format.
69+
An object for writing MSW's [request handler](https://mswjs.io/docs/concepts/request-handler). Essentially, it is a thin wrapper for MSW's [`http`](https://mswjs.io/docs/api/http). The usage is almost identical to `http`, but paths and methods are expressed in an aspida-like format.
6070

6171
```ts
62-
const handler = typedRest.products._productId.images.$post((req, res, ctx) => ...);
72+
const handler = typedHttp.products._productId.images.$post(({ request, params }) => ...);
6373

6474
// This is equivalent to:
65-
const handler = rest.post('https://example.com/products/:productId/images', (req, res, ctx) => ...);
75+
const handler = http.post('https://example.com/products/:productId/images', ({ request, params }) => ...);
6676
```
6777

6878
#### Path
@@ -72,36 +82,36 @@ Paths are expressed as properties. While path parameters are expressed with func
7282
Use `.$path()` to get the path of that endpoint as a string.
7383

7484
```ts
75-
const path = typedRest.products._productId.images.$path();
85+
const path = typedHttp.products._productId.images.$path();
7686
// -> 'https://example.com/products/:productId/images'
7787
```
7888

7989
#### Method
8090

81-
Expressed as the `$`-prefixed HTTP method function, like `.$get(resolver)` or `.$post(resolver)`. The argument is MSW's [response resolver](https://v1.mswjs.io/docs/basics/response-resolver). The following three are typed from aspida's `api`, so no type annotations are required:
91+
Expressed as the `$`-prefixed HTTP method function, like `.$get(resolver)` or `.$post(resolver)`. The argument is MSW's [response resolver](https://mswjs.io/docs/concepts/response-resolver). The following three are typed from aspida's `api`, so no type annotations are required:
8292

83-
- Path parameters `req.params`
93+
- Path parameters: [`params`](https://mswjs.io/docs/network-behavior/rest#reading-path-parameters)
8494
- As per MSW's behavior, the type of value is always `string`.
85-
- Request body `req.body`
86-
- Note that for `await req.json()`, [the type is always `any`](https://github.com/mswjs/msw/issues/1318#issuecomment-1205149710).
87-
- Response body `res(ctx.json())`
95+
- Request body: [`await request.json()`](https://mswjs.io/docs/network-behavior/rest#reading-request-body)
96+
- Response body: the first argument of [`HttpResponse.json()`](https://mswjs.io/docs/api/http-response#httpresponsejsonbody-init)
8897

8998
```ts
90-
const handler = typedRest.products._productId.images.$post((req, res, ctx) => {
91-
console.log(`Add an image to product ${req.params.productId}`); // Path parameter is typed ✅
92-
console.log(`Image description: ${req.body.description}`); // Request body is typed ✅
93-
return res(
94-
ctx.status(201),
95-
ctx.json({ id: 123, ...req.body }), // Response body is also typed ✅
96-
);
97-
});
98-
```
99+
const handler = typedHttp.products._productId.images.$post(
100+
({ request, params }) => {
101+
console.log(`Add an image to product ${params.productId}`); // Path parameter is typed ✅
99102

100-
## FAQ
103+
const reqBody = await request.json();
104+
console.log(`Image description: ${reqBody.description}`); // Request body is typed ✅
101105

102-
### Is it compatible with MSW 2.x?
106+
return HttpResponse.json(
107+
{ id: 123, ...reqBody }, // Response body is also typed ✅
108+
{ status: 201 },
109+
);
110+
},
111+
);
112+
```
103113

104-
Not yet, but [it's planned](https://github.com/mashabow/mswpida/issues/13).
114+
## FAQ
105115

106116
### How can I return an error response without getting a type error?
107117

@@ -110,16 +120,24 @@ By using method with a type parameter like `.$get<T>()` or `.$post<T>()`, you ca
110120
```ts
111121
type ErrorResponseBody = { errorCode: string };
112122

113-
const handler = typedRest.products._productId.images.$post<ErrorResponseBody>(
114-
(req, res, ctx) => {
115-
if (req.params.productId === 'bad_id') {
116-
return res(ctx.status(404), ctx.json({ errorCode: 'product_not_found' }));
123+
const handler = typedHttp.products._productId.images.$post<ErrorResponseBody>(
124+
({ request, params }) => {
125+
if (params.productId === 'bad_id') {
126+
return HttpResponse.json(
127+
{ errorCode: 'product_not_found' },
128+
{ status: 404 },
129+
);
117130
}
118-
return res(ctx.status(201), ctx.json({ id: 123, ...req.body }));
131+
const reqBody = await request.json();
132+
return HttpResponse.json({ id: 123, ...reqBody }, { status: 201 });
119133
},
120134
);
121135
```
122136

137+
### Can I use it with MSW v1?
138+
139+
Please use mswpida v1 for MSW v1.
140+
123141
## License
124142

125143
MIT

0 commit comments

Comments
 (0)