This commit is contained in:
syuilo 2021-05-23 12:32:58 +09:00
parent e7eac5baa7
commit 8d3f9d7e34
2 changed files with 40 additions and 6 deletions

View File

@ -33,14 +33,12 @@ export class APIClient {
endpoint: E, data: Endpoints[E]['req'] = {}, credential?: string | null | undefined, endpoint: E, data: Endpoints[E]['req'] = {}, credential?: string | null | undefined,
): Promise<Endpoints[E]['res']> { ): Promise<Endpoints[E]['res']> {
const promise = new Promise<Endpoints[E]['res']>((resolve, reject) => { 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}`, { this.fetch(`${this.origin}/api/${endpoint}`, {
method: 'POST', method: 'POST',
body: JSON.stringify(data), body: JSON.stringify({
...data,
i: credential !== undefined ? credential : this.credential
}),
credentials: 'omit', credentials: 'omit',
cache: 'no-cache' cache: 'no-cache'
}).then(async (res) => { }).then(async (res) => {

View File

@ -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 () => { test('api error', async () => {
fetchMock.resetMocks(); fetchMock.resetMocks();
fetchMock.mockResponse(async (req) => { fetchMock.mockResponse(async (req) => {