(refactor) api呼び出し関数のレスポンス型を必要に応じてオーバーライドできるように (#12936)

This commit is contained in:
かっこかり 2024-01-08 08:13:36 +09:00 committed by GitHub
parent 0e536bdd86
commit 5251cd3aad
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -10,12 +10,17 @@ import { $i } from '@/account.js';
export const pendingApiRequestsCount = ref(0);
// Implements Misskey.api.ApiClient.request
export function misskeyApi<E extends keyof Misskey.Endpoints, P extends Misskey.Endpoints[E]['req']>(
export function misskeyApi<
ResT = void,
E extends keyof Misskey.Endpoints = keyof Misskey.Endpoints,
P extends Misskey.Endpoints[E]['req'] = Misskey.Endpoints[E]['req'],
_ResT = ResT extends void ? Misskey.api.SwitchCaseResponseType<E, P> : ResT,
>(
endpoint: E,
data: P = {} as any,
token?: string | null | undefined,
signal?: AbortSignal,
): Promise<Misskey.api.SwitchCaseResponseType<E, P>> {
): Promise<_ResT> {
if (endpoint.includes('://')) throw new Error('invalid endpoint');
pendingApiRequestsCount.value++;
@ -23,7 +28,7 @@ export function misskeyApi<E extends keyof Misskey.Endpoints, P extends Misskey.
pendingApiRequestsCount.value--;
};
const promise = new Promise<Misskey.Endpoints[E]['res'] | void>((resolve, reject) => {
const promise = new Promise<_ResT>((resolve, reject) => {
// Append a credential
if ($i) (data as any).i = $i.token;
if (token !== undefined) (data as any).i = token;
@ -44,7 +49,7 @@ export function misskeyApi<E extends keyof Misskey.Endpoints, P extends Misskey.
if (res.status === 200) {
resolve(body);
} else if (res.status === 204) {
resolve();
resolve(undefined as _ResT); // void -> undefined
} else {
reject(body.error);
}
@ -57,10 +62,15 @@ export function misskeyApi<E extends keyof Misskey.Endpoints, P extends Misskey.
}
// Implements Misskey.api.ApiClient.request
export function misskeyApiGet<E extends keyof Misskey.Endpoints, P extends Misskey.Endpoints[E]['req']>(
export function misskeyApiGet<
ResT = void,
E extends keyof Misskey.Endpoints = keyof Misskey.Endpoints,
P extends Misskey.Endpoints[E]['req'] = Misskey.Endpoints[E]['req'],
_ResT = ResT extends void ? Misskey.api.SwitchCaseResponseType<E, P> : ResT,
>(
endpoint: E,
data: P = {} as any,
): Promise<Misskey.api.SwitchCaseResponseType<E, P>> {
): Promise<_ResT> {
pendingApiRequestsCount.value++;
const onFinally = () => {
@ -69,7 +79,7 @@ export function misskeyApiGet<E extends keyof Misskey.Endpoints, P extends Missk
const query = new URLSearchParams(data as any);
const promise = new Promise<Misskey.Endpoints[E]['res'] | void>((resolve, reject) => {
const promise = new Promise<_ResT>((resolve, reject) => {
// Send request
window.fetch(`${apiUrl}/${endpoint}?${query}`, {
method: 'GET',
@ -81,7 +91,7 @@ export function misskeyApiGet<E extends keyof Misskey.Endpoints, P extends Missk
if (res.status === 200) {
resolve(body);
} else if (res.status === 204) {
resolve();
resolve(undefined as _ResT); // void -> undefined
} else {
reject(body.error);
}