Skip to content

Commit 1b72a59

Browse files
authored
Merge pull request #39 from himorishige/feat/use-cross-fetch
node-fetchからcross-fetchへの変更
2 parents e486b30 + 05a96f6 commit 1b72a59

File tree

10 files changed

+135
-98
lines changed

10 files changed

+135
-98
lines changed

.node-version

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
v14.20.0

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ const { createClient } = microcms;
4747
const client = createClient({
4848
serviceDomain: "YOUR_DOMAIN", // YOUR_DOMAIN is the XXXX part of XXXX.microcms.io
4949
apiKey: "YOUR_API_KEY",
50+
// customFetcher: fetch.bind(globalThis), // Provide a custom `fetch` implementation as an option
5051
});
5152
</script>
5253
```

package-lock.json

Lines changed: 17 additions & 66 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
"dist"
3030
],
3131
"dependencies": {
32-
"node-fetch": "^2.6.1",
32+
"cross-fetch": "^3.1.5",
3333
"qs": "^6.10.1"
3434
},
3535
"devDependencies": {
@@ -39,7 +39,6 @@
3939
"@rollup/plugin-node-resolve": "^13.0.0",
4040
"@types/jest": "^28.1.6",
4141
"@types/node": "^15.0.2",
42-
"@types/node-fetch": "^2.5.10",
4342
"@types/qs": "^6.9.6",
4443
"@typescript-eslint/eslint-plugin": "^4.22.1",
4544
"@typescript-eslint/parser": "^4.22.1",

src/createClient.ts

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
* microCMS API SDK
33
* https://github.com/microcmsio/microcms-js-sdk
44
*/
5-
import fetch, { RequestInit } from 'node-fetch';
65
import { parseQuery } from './utils/parseQuery';
76
import { isString } from './utils/isCheckValue';
87
import {
@@ -21,11 +20,16 @@ import {
2120
DeleteRequest,
2221
} from './types';
2322
import { API_VERSION, BASE_DOMAIN } from './utils/constants';
23+
import { generateFetchClient } from './lib/fetch';
2424

2525
/**
2626
* Initialize SDK Client
2727
*/
28-
export const createClient = ({ serviceDomain, apiKey }: MicroCMSClient) => {
28+
export const createClient = ({
29+
serviceDomain,
30+
apiKey,
31+
customFetch,
32+
}: MicroCMSClient) => {
2933
if (!serviceDomain || !apiKey) {
3034
throw new Error('parameter is required (check serviceDomain and apiKey)');
3135
}
@@ -50,20 +54,19 @@ export const createClient = ({ serviceDomain, apiKey }: MicroCMSClient) => {
5054
customHeaders,
5155
customBody,
5256
}: MakeRequest) => {
53-
const queryString = parseQuery(queries);
54-
55-
const baseHeaders: RequestInit = {
56-
headers: { ...customHeaders, 'X-MICROCMS-API-KEY': apiKey },
57-
body: customBody,
58-
method,
59-
};
57+
const fetchClient = generateFetchClient(apiKey, customFetch);
6058

59+
const queryString = parseQuery(queries);
6160
const url = `${baseUrl}/${endpoint}${contentId ? `/${contentId}` : ''}${
6261
queryString ? `?${queryString}` : ''
6362
}`;
6463

6564
try {
66-
const response = await fetch(url, baseHeaders);
65+
const response = await fetchClient(url, {
66+
method: method || 'GET',
67+
headers: customHeaders,
68+
body: customBody,
69+
});
6770

6871
if (!response.ok) {
6972
throw new Error(`fetch API response status: ${response.status}`);
@@ -179,7 +182,7 @@ export const createClient = ({ serviceDomain, apiKey }: MicroCMSClient) => {
179182
};
180183

181184
/**
182-
* Update content in ther microCMS list and object API data
185+
* Update content in their microCMS list and object API data
183186
*/
184187
const update = async <T extends Record<string | number, any>>({
185188
endpoint,
@@ -206,7 +209,7 @@ export const createClient = ({ serviceDomain, apiKey }: MicroCMSClient) => {
206209
};
207210

208211
/**
209-
* Delete content in ther microCMS list and object API data
212+
* Delete content in their microCMS list and object API data
210213
*/
211214
const _delete = async ({
212215
endpoint,

src/lib/fetch.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import crossFetch, { Headers as CrossFetchHeaders } from 'cross-fetch';
2+
import { Fetch } from 'src/types';
3+
4+
export const resolveFetch = (customFetch?: Fetch): Fetch => {
5+
let _fetch: Fetch;
6+
if (customFetch) {
7+
_fetch = customFetch;
8+
} else if (typeof fetch === 'undefined') {
9+
_fetch = (crossFetch as unknown) as Fetch;
10+
} else {
11+
_fetch = fetch;
12+
}
13+
return (...args) => _fetch(...args);
14+
};
15+
16+
export const resolveHeadersConstructor = () => {
17+
if (typeof Headers === 'undefined') {
18+
return CrossFetchHeaders;
19+
}
20+
21+
return Headers;
22+
};
23+
24+
export const generateFetchClient = (
25+
apiKey: string,
26+
customFetch?: Fetch
27+
): Fetch => {
28+
const fetch = resolveFetch(customFetch);
29+
const HeadersConstructor = resolveHeadersConstructor();
30+
31+
return async (req, init) => {
32+
const headers = new HeadersConstructor(init?.headers);
33+
34+
if (!headers.has('X-MICROCMS-API-KEY')) {
35+
headers.set('X-MICROCMS-API-KEY', apiKey);
36+
}
37+
38+
return fetch(req, { ...init, headers });
39+
};
40+
};

src/types.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
import { BodyInit, HeadersInit } from 'node-fetch';
1+
export type Fetch = typeof fetch;
22

33
/**
44
* microCMS createClient params
55
*/
66
export interface MicroCMSClient {
77
serviceDomain: string;
88
apiKey: string;
9+
customFetch?: Fetch;
910
}
1011

1112
type depthNumber = 1 | 2 | 3;
@@ -80,7 +81,7 @@ export interface MakeRequest {
8081
queries?: MicroCMSQueries & Record<string, any>;
8182
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
8283
customHeaders?: HeadersInit;
83-
customBody?: BodyInit;
84+
customBody?: string;
8485
}
8586

8687
export interface GetRequest {

tests/createClient.test.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ describe('createClient', () => {
55
const client = createClient({
66
serviceDomain: 'serviceDomain',
77
apiKey: 'apiKey',
8+
customFetch: () => Promise.resolve(new Response()),
89
});
910

1011
expect(typeof client.get === 'function').toBe(true);

tests/lib/fetch.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { generateFetchClient } from '../../src/lib/fetch';
2+
3+
describe('generateFetchClient', () => {
4+
test('If no options is specified, cross-fetch is used', async () => {
5+
const client = generateFetchClient('apiKey');
6+
const response = await client('http://example.com');
7+
expect(response.status).toBe(200);
8+
});
9+
10+
test('If custom fetch is specified, custom fetch is used', async () => {
11+
const customFetch = jest.fn();
12+
const client = generateFetchClient('apiKey', customFetch);
13+
await client('http://example.com');
14+
expect(customFetch).toHaveBeenCalled();
15+
});
16+
});

0 commit comments

Comments
 (0)