feat(misskey-js): エラーを型として出力するように
This commit is contained in:
parent
bf403aa656
commit
1dfe08a8c1
12 changed files with 6817 additions and 1210 deletions
|
|
@ -24,55 +24,89 @@ import MkContextMenu from '@/components/MkContextMenu.vue';
|
|||
import { MenuItem } from '@/types/menu.js';
|
||||
import copyToClipboard from '@/scripts/copy-to-clipboard.js';
|
||||
import { showMovedDialog } from '@/scripts/show-moved-dialog.js';
|
||||
import { ErrPromise } from '@/scripts/err-promise.js';
|
||||
|
||||
export const openingWindowsCount = ref(0);
|
||||
|
||||
export const apiWithDialog = (<E extends keyof Misskey.Endpoints = keyof Misskey.Endpoints, P extends Misskey.Endpoints[E]['req'] = Misskey.Endpoints[E]['req']>(
|
||||
type CustomErrorDef<T> = {
|
||||
[key in T extends { code: infer C; } ? C extends string ? C : string : string]?: { title?: string; text: string; };
|
||||
};
|
||||
|
||||
export function apiWithDialog<
|
||||
E extends keyof Misskey.Endpoints = keyof Misskey.Endpoints,
|
||||
P extends Misskey.Endpoints[E]['req'] = Misskey.Endpoints[E]['req'],
|
||||
ER extends Misskey.Endpoints[E]['errors'] = Misskey.Endpoints[E]['errors'],
|
||||
>(
|
||||
endpoint: E,
|
||||
data: P = {} as any,
|
||||
token?: string | null | undefined,
|
||||
) => {
|
||||
customErrors?: CustomErrorDef<ER>,
|
||||
) {
|
||||
const promise = misskeyApi(endpoint, data, token);
|
||||
promiseDialog(promise, null, async (err) => {
|
||||
let title: string | undefined;
|
||||
let text = err.message + '\n' + err.id;
|
||||
if (err.code === 'INTERNAL_ERROR') {
|
||||
title = i18n.ts.internalServerError;
|
||||
text = i18n.ts.internalServerErrorDescription;
|
||||
const date = new Date().toISOString();
|
||||
const { result } = await actions({
|
||||
type: 'error',
|
||||
title,
|
||||
text,
|
||||
actions: [{
|
||||
value: 'ok',
|
||||
text: i18n.ts.gotIt,
|
||||
primary: true,
|
||||
}, {
|
||||
value: 'copy',
|
||||
text: i18n.ts.copyErrorInfo,
|
||||
}],
|
||||
});
|
||||
if (result === 'copy') {
|
||||
copyToClipboard(`Endpoint: ${endpoint}\nInfo: ${JSON.stringify(err.info)}\nDate: ${date}`);
|
||||
success();
|
||||
let text: string;
|
||||
|
||||
const initialText: string[] = [];
|
||||
if ('message' in err && err.message != null) {
|
||||
initialText.push(err.message);
|
||||
}
|
||||
if ('id' in err && err.id != null) {
|
||||
initialText.push(err.id);
|
||||
}
|
||||
text = initialText.join('\n');
|
||||
|
||||
if ('code' in err && err.code != null) {
|
||||
if (err.code === 'INTERNAL_ERROR') {
|
||||
title = i18n.ts.internalServerError;
|
||||
text = i18n.ts.internalServerErrorDescription;
|
||||
const date = new Date().toISOString();
|
||||
const { result } = await actions({
|
||||
type: 'error',
|
||||
title,
|
||||
text,
|
||||
actions: [{
|
||||
value: 'ok',
|
||||
text: i18n.ts.gotIt,
|
||||
primary: true,
|
||||
}, {
|
||||
value: 'copy',
|
||||
text: i18n.ts.copyErrorInfo,
|
||||
}],
|
||||
});
|
||||
if (result === 'copy') {
|
||||
const text = [
|
||||
`Endpoint: ${endpoint}`,
|
||||
('info' in err) ? `Info: ${JSON.stringify(err.info)}` : undefined,
|
||||
`Date: ${date}`,
|
||||
].filter(x => x != null);
|
||||
copyToClipboard(text.join('\n'));
|
||||
success();
|
||||
}
|
||||
return;
|
||||
} else if (err.code === 'RATE_LIMIT_EXCEEDED') {
|
||||
title = i18n.ts.cannotPerformTemporary;
|
||||
text = i18n.ts.cannotPerformTemporaryDescription;
|
||||
} else if (err.code === 'INVALID_PARAM') {
|
||||
title = i18n.ts.invalidParamError;
|
||||
text = i18n.ts.invalidParamErrorDescription;
|
||||
} else if (err.code === 'ROLE_PERMISSION_DENIED') {
|
||||
title = i18n.ts.permissionDeniedError;
|
||||
text = i18n.ts.permissionDeniedErrorDescription;
|
||||
} else if (customErrors && customErrors[err.code] != null) {
|
||||
title = customErrors[err.code].title;
|
||||
text = customErrors[err.code].text;
|
||||
} else if (err.code.startsWith('TOO_MANY')) {
|
||||
title = i18n.ts.youCannotCreateAnymore;
|
||||
if ('id' in err && err.id != null) {
|
||||
text = `${i18n.ts.error}: ${err.id}`;
|
||||
} else {
|
||||
text = `${i18n.ts.error}`;
|
||||
}
|
||||
} else if (err.message.startsWith('Unexpected token')) {
|
||||
title = i18n.ts.gotInvalidResponseError;
|
||||
text = i18n.ts.gotInvalidResponseErrorDescription;
|
||||
}
|
||||
return;
|
||||
} else if (err.code === 'RATE_LIMIT_EXCEEDED') {
|
||||
title = i18n.ts.cannotPerformTemporary;
|
||||
text = i18n.ts.cannotPerformTemporaryDescription;
|
||||
} else if (err.code === 'INVALID_PARAM') {
|
||||
title = i18n.ts.invalidParamError;
|
||||
text = i18n.ts.invalidParamErrorDescription;
|
||||
} else if (err.code === 'ROLE_PERMISSION_DENIED') {
|
||||
title = i18n.ts.permissionDeniedError;
|
||||
text = i18n.ts.permissionDeniedErrorDescription;
|
||||
} else if (err.code.startsWith('TOO_MANY')) {
|
||||
title = i18n.ts.youCannotCreateAnymore;
|
||||
text = `${i18n.ts.error}: ${err.id}`;
|
||||
} else if (err.message.startsWith('Unexpected token')) {
|
||||
title = i18n.ts.gotInvalidResponseError;
|
||||
text = i18n.ts.gotInvalidResponseErrorDescription;
|
||||
}
|
||||
alert({
|
||||
type: 'error',
|
||||
|
|
@ -82,12 +116,16 @@ export const apiWithDialog = (<E extends keyof Misskey.Endpoints = keyof Misskey
|
|||
});
|
||||
|
||||
return promise;
|
||||
}) as typeof misskeyApi;
|
||||
}
|
||||
|
||||
export function promiseDialog<T extends Promise<any>>(
|
||||
export function promiseDialog<
|
||||
T extends ErrPromise<any, any> | Promise<any>,
|
||||
R = T extends ErrPromise<infer R, unknown> ? R : T extends Promise<infer R> ? R : never,
|
||||
E = T extends ErrPromise<unknown, infer E> ? E : T extends Promise<unknown> ? any : never,
|
||||
>(
|
||||
promise: T,
|
||||
onSuccess?: ((res: any) => void) | null,
|
||||
onFailure?: ((err: Misskey.api.APIError) => void) | null,
|
||||
onSuccess?: ((res: R) => void) | null,
|
||||
onFailure?: ((err: E) => void) | null,
|
||||
text?: string,
|
||||
): T {
|
||||
const showing = ref(true);
|
||||
|
|
|
|||
18
packages/frontend/src/scripts/err-promise.ts
Normal file
18
packages/frontend/src/scripts/err-promise.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
|
||||
export interface IErrPromise<TSuccess, TError = unknown> {
|
||||
then<TResult1 = TSuccess, TResult2 = never>(onfulfilled?: ((value: TSuccess) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: TError) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
|
||||
|
||||
catch<TResult = never>(onrejected?: ((reason: TError) => TResult | PromiseLike<TResult>) | undefined | null): Promise<TSuccess | TResult>;
|
||||
}
|
||||
|
||||
/** rejectに型付けができるPromise */
|
||||
export class ErrPromise<TSuccess, TError> extends Promise<TSuccess> implements IErrPromise<TSuccess, TError> {
|
||||
constructor(executor: (resolve: (value: TSuccess | PromiseLike<TSuccess>) => void, reject: (reason: TError) => void) => void) {
|
||||
super(executor);
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ import * as Misskey from 'misskey-js';
|
|||
import { ref } from 'vue';
|
||||
import { apiUrl } from '@/config.js';
|
||||
import { $i } from '@/account.js';
|
||||
import { ErrPromise } from '@/scripts/err-promise.js';
|
||||
export const pendingApiRequestsCount = ref(0);
|
||||
|
||||
// Implements Misskey.api.ApiClient.request
|
||||
|
|
@ -14,13 +15,14 @@ export function misskeyApi<
|
|||
ResT = void,
|
||||
E extends keyof Misskey.Endpoints = keyof Misskey.Endpoints,
|
||||
P extends Misskey.Endpoints[E]['req'] = Misskey.Endpoints[E]['req'],
|
||||
RE extends Misskey.Endpoints[E]['errors'] = Misskey.Endpoints[E]['errors'],
|
||||
_ResT = ResT extends void ? Misskey.api.SwitchCaseResponseType<E, P> : ResT,
|
||||
>(
|
||||
endpoint: E,
|
||||
data: P = {} as any,
|
||||
token?: string | null | undefined,
|
||||
signal?: AbortSignal,
|
||||
): Promise<_ResT> {
|
||||
): ErrPromise<_ResT, RE> {
|
||||
if (endpoint.includes('://')) throw new Error('invalid endpoint');
|
||||
pendingApiRequestsCount.value++;
|
||||
|
||||
|
|
@ -28,7 +30,7 @@ export function misskeyApi<
|
|||
pendingApiRequestsCount.value--;
|
||||
};
|
||||
|
||||
const promise = new Promise<_ResT>((resolve, reject) => {
|
||||
const promise = new ErrPromise<_ResT, RE>((resolve, reject) => {
|
||||
// Append a credential
|
||||
if ($i) (data as any).i = $i.token;
|
||||
if (token !== undefined) (data as any).i = token;
|
||||
|
|
@ -47,7 +49,7 @@ export function misskeyApi<
|
|||
const body = res.status === 204 ? null : await res.json();
|
||||
|
||||
if (res.status === 200) {
|
||||
resolve(body);
|
||||
resolve(body as _ResT);
|
||||
} else if (res.status === 204) {
|
||||
resolve(undefined as _ResT); // void -> undefined
|
||||
} else {
|
||||
|
|
@ -66,11 +68,12 @@ export function misskeyApiGet<
|
|||
ResT = void,
|
||||
E extends keyof Misskey.Endpoints = keyof Misskey.Endpoints,
|
||||
P extends Misskey.Endpoints[E]['req'] = Misskey.Endpoints[E]['req'],
|
||||
RE extends Misskey.Endpoints[E]['errors'] = Misskey.Endpoints[E]['errors'],
|
||||
_ResT = ResT extends void ? Misskey.api.SwitchCaseResponseType<E, P> : ResT,
|
||||
>(
|
||||
endpoint: E,
|
||||
data: P = {} as any,
|
||||
): Promise<_ResT> {
|
||||
): ErrPromise<_ResT, RE> {
|
||||
pendingApiRequestsCount.value++;
|
||||
|
||||
const onFinally = () => {
|
||||
|
|
@ -79,7 +82,7 @@ export function misskeyApiGet<
|
|||
|
||||
const query = new URLSearchParams(data as any);
|
||||
|
||||
const promise = new Promise<_ResT>((resolve, reject) => {
|
||||
const promise = new ErrPromise<_ResT, RE>((resolve, reject) => {
|
||||
// Send request
|
||||
window.fetch(`${apiUrl}/${endpoint}?${query}`, {
|
||||
method: 'GET',
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue