summaryrefslogtreecommitdiff
path: root/packages/misskey-js/test/api.ts
blob: 1a7574de25e75a289438c6e654d801a0e5fee8cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import { enableFetchMocks } from 'jest-fetch-mock';
import { APIClient, isAPIError } from '../src/api.js';

enableFetchMocks();

function getFetchCall(call: any[]) {
	const { body, method } = call[1];
	const contentType = call[1].headers['Content-Type'];
	if (
		body == null ||
		(contentType === 'application/json' && typeof body !== 'string') ||
		(contentType === 'multipart/form-data' && !(body instanceof FormData))
	) {
		throw new Error('invalid body');
	}
	return {
		url: call[0],
		method: method,
		contentType: contentType,
		body: body instanceof FormData ? Object.fromEntries(body.entries()) : JSON.parse(body),
	};
}

describe('API', () => {
	test('success', async () => {
		fetchMock.resetMocks();
		fetchMock.mockResponse(async (req) => {
			const body = await req.json();
			if (req.method == 'POST' && req.url == 'https://misskey.test/api/i') {
				if (body.i === 'TOKEN') {
					return JSON.stringify({ id: 'foo' });
				} else {
					return { status: 400 };
				}
			} else {
				return { status: 404 };
			}
		});

		const cli = new APIClient({
			origin: 'https://misskey.test',
			credential: 'TOKEN',
		});

		const res = await cli.request('i');

		expect(res).toEqual({
			id: 'foo'
		});

		expect(getFetchCall(fetchMock.mock.calls[0])).toEqual({
			url: 'https://misskey.test/api/i',
			method: 'POST',
			contentType: 'application/json',
			body: { i: 'TOKEN' }
		});
	});

	test('with params', async () => {
		fetchMock.resetMocks();
		fetchMock.mockResponse(async (req) => {
			const body = await req.json();
			if (req.method == 'POST' && req.url == 'https://misskey.test/api/notes/show') {
				if (body.i === 'TOKEN' && body.noteId === 'aaaaa') {
					return JSON.stringify({ id: 'foo' });
				} else {
					return { status: 400 };
				}
			} else {
				return { status: 404 };
			}
		});

		const cli = new APIClient({
			origin: 'https://misskey.test',
			credential: 'TOKEN',
		});

		const res = await cli.request('notes/show', { noteId: 'aaaaa' });

		expect(res).toEqual({
			id: 'foo'
		});

		expect(getFetchCall(fetchMock.mock.calls[0])).toEqual({
			url: 'https://misskey.test/api/notes/show',
			method: 'POST',
			contentType: 'application/json',
			body: { i: 'TOKEN', noteId: 'aaaaa' }
		});
	});

	test('multipart/form-data', async () => {
		fetchMock.resetMocks();
		fetchMock.mockResponse(async (req) => {
			if (req.method == 'POST' && req.url == 'https://misskey.test/api/drive/files/create') {
				if (req.headers.get('Content-Type')?.includes('multipart/form-data')) {
					return JSON.stringify({ id: 'foo' });
				} else {
					return { status: 400 };
				}
			} else {
				return { status: 404 };
			}
		});

		const cli = new APIClient({
			origin: 'https://misskey.test',
			credential: 'TOKEN',
		});

		const testFile = new File([], 'foo.txt');

		const res = await cli.request('drive/files/create', {
			file: testFile,
			name: null, // nullのパラメータは消える
		});

		expect(res).toEqual({
			id: 'foo'
		});

		expect(getFetchCall(fetchMock.mock.calls[0])).toEqual({
			url: 'https://misskey.test/api/drive/files/create',
			method: 'POST',
			contentType: 'multipart/form-data',
			body: {
				i: 'TOKEN',
				file: testFile,
			}
		});
	});

	test('204 No Content で null が返る', async () => {
		fetchMock.resetMocks();
		fetchMock.mockResponse(async (req) => {
			if (req.method == 'POST' && req.url == 'https://misskey.test/api/reset-password') {
				return { status: 204 };
			} else {
				return { status: 404 };
			}
		});

		const cli = new APIClient({
			origin: 'https://misskey.test',
			credential: 'TOKEN',
		});

		const res = await cli.request('reset-password', { token: 'aaa', password: 'aaa' });

		expect(res).toEqual(null);

		expect(getFetchCall(fetchMock.mock.calls[0])).toEqual({
			url: 'https://misskey.test/api/reset-password',
			method: 'POST',
			contentType: 'application/json',
			body: { i: 'TOKEN', token: 'aaa', password: 'aaa' }
		});
	});

	test('インスタンスの credential が指定されていても引数で credential が null ならば null としてリクエストされる', async () => {
		fetchMock.resetMocks();
		fetchMock.mockResponse(async (req) => {
			const body = await req.json();
			if (req.method == 'POST' && req.url == 'https://misskey.test/api/i') {
				if (typeof body.i === 'string') {
					return JSON.stringify({ id: 'foo' });
				} else {
					return {
						status: 401,
						body: JSON.stringify({
							error: {
								message: 'Credential required.',
								code: 'CREDENTIAL_REQUIRED',
								id: '1384574d-a912-4b81-8601-c7b1c4085df1',
							}
						})
					};
				}
			} else {
				return { status: 404 };
			}
		});

		try {
			const cli = new APIClient({
				origin: 'https://misskey.test',
				credential: 'TOKEN',
			});

			await cli.request('i', {}, null);
		} catch (e) {
			expect(isAPIError(e)).toEqual(true);
		}
	});

	test('api error', async () => {
		fetchMock.resetMocks();
		fetchMock.mockResponse(async (req) => {
			return {
				status: 500,
				body: JSON.stringify({
					error: {
						message: 'Internal error occurred. Please contact us if the error persists.',
						code: 'INTERNAL_ERROR',
						id: '5d37dbcb-891e-41ca-a3d6-e690c97775ac',
						kind: 'server',
					},
				})
			};
		});

		try {
			const cli = new APIClient({
				origin: 'https://misskey.test',
				credential: 'TOKEN',
			});

			await cli.request('i');
		} catch (e: any) {
			expect(isAPIError(e)).toEqual(true);
			expect(e.id).toEqual('5d37dbcb-891e-41ca-a3d6-e690c97775ac');
		}
	});

	test('network error', async () => {
		fetchMock.resetMocks();
		fetchMock.mockAbort();

		try {
			const cli = new APIClient({
				origin: 'https://misskey.test',
				credential: 'TOKEN',
			});

			await cli.request('i');
		} catch (e) {
			expect(isAPIError(e)).toEqual(false);
		}
	});

	test('json parse error', async () => {
		fetchMock.resetMocks();
		fetchMock.mockResponse(async (req) => {
			return {
				status: 500,
				body: '<html>I AM NOT JSON</html>'
			};
		});

		try {
			const cli = new APIClient({
				origin: 'https://misskey.test',
				credential: 'TOKEN',
			});

			await cli.request('i');
		} catch (e) {
			expect(isAPIError(e)).toEqual(false);
		}
	});

	test('admin/roles/create の型が合う', async() => {
		fetchMock.resetMocks();
		fetchMock.mockResponse(async () => {
			return {
				// 本来返すべき値は`Role`型だが、テストなのでお茶を濁す
				status: 200,
				body: '{}'
			};
		});

		const cli = new APIClient({
			origin: 'https://misskey.test',
			credential: 'TOKEN',
		});
		await cli.request('admin/roles/create', {
			name: 'aaa',
			asBadge: false,
			canEditMembersByModerator: false,
			color: '#123456',
			condFormula: {},
			description: '',
			displayOrder: 0,
			iconUrl: '',
			isAdministrator: false,
			isExplorable: false,
			isModerator: false,
			isPublic: false,
			policies: {
				ltlAvailable: {
					value: true,
					priority: 0,
					useDefault: false,
				},
			},
			target: 'manual',
		});
	})
});