From 8d3f9d7e34c2e19bf0602cd8a20bbd61cc9f744f Mon Sep 17 00:00:00 2001
From: syuilo <Syuilotan@yahoo.co.jp>
Date: Sun, 23 May 2021 12:32:58 +0900
Subject: [PATCH] :v:

---
 src/api.ts  | 10 ++++------
 test/api.ts | 36 ++++++++++++++++++++++++++++++++++++
 2 files changed, 40 insertions(+), 6 deletions(-)

diff --git a/src/api.ts b/src/api.ts
index 0a106ae914..e59ff1710d 100644
--- a/src/api.ts
+++ b/src/api.ts
@@ -33,14 +33,12 @@ export class APIClient {
 		endpoint: E, data: Endpoints[E]['req'] = {}, credential?: string | null | undefined,
 	): Promise<Endpoints[E]['res']> {
 		const promise = new Promise<Endpoints[E]['res']>((resolve, reject) => {
-			// Append a credential
-			if (this.credential) (data as Record<string, any>).i = this.credential;
-			if (credential) (data as Record<string, any>).i = credential;
-	
-			// Send request
 			this.fetch(`${this.origin}/api/${endpoint}`, {
 				method: 'POST',
-				body: JSON.stringify(data),
+				body: JSON.stringify({
+					...data,
+					i: credential !== undefined ? credential : this.credential
+				}),
 				credentials: 'omit',
 				cache: 'no-cache'
 			}).then(async (res) => {
diff --git a/test/api.ts b/test/api.ts
index 3380f3b630..8b27c54ed1 100644
--- a/test/api.ts
+++ b/test/api.ts
@@ -51,6 +51,42 @@ describe('API', () => {
 		});
 	});
 
+	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) => {
-- 
GitLab