don't use ErrPromise

This commit is contained in:
kakkokari-gtyih 2024-06-23 14:34:16 +09:00
parent 7aad04377d
commit f926640b3b
9 changed files with 885 additions and 873 deletions

View file

@ -58,6 +58,7 @@ import { miLocalStorage } from '@/local-storage.js';
import { customEmojis } from '@/custom-emojis.js';
import { MFM_TAGS, MFM_PARAMS } from '@/const.js';
import { searchEmoji, EmojiDef } from '@/scripts/search-emoji.js';
import { isAPIError } from 'misskey-js/api.js';
const lib = emojilist.filter(x => x.category !== 'flags');
@ -206,6 +207,10 @@ function exec() {
fetching.value = false;
//
sessionStorage.setItem(cacheKey, JSON.stringify(searchedUsers));
}).catch((err) => {
if (isAPIError(err)) {
console.error(err);
}
});
}
} else if (props.type === 'hashtag') {

View file

@ -24,7 +24,6 @@ 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);
@ -43,7 +42,7 @@ export function apiWithDialog<
customErrors?: CustomErrorDef<ER>,
) {
const promise = misskeyApi(endpoint, data, token);
promiseDialog(promise, null, async (err) => {
promiseDialog(promise, null, async (err: Error) => {
let title: string | undefined;
let text: string;
@ -51,57 +50,63 @@ export function apiWithDialog<
if ('message' in err && err.message != null) {
initialText.push(err.message);
}
if ('id' in err && err.id != null) {
initialText.push(err.id);
if (Misskey.api.isAPIError<ER>(err) && 'id' in err.payload && err.payload.id != null) {
initialText.push(err.payload.id);
}
text = initialText.join('\n');
if ('code' in err && err.code != null) {
if (customErrors && customErrors[err.code] != null) {
title = customErrors[err.code].title;
text = customErrors[err.code].text;
} else 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 (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}`;
if (Misskey.api.isAPIError<ER>(err)) {
const { payload } = err;
if ('code' in payload && payload.code != null) {
if (customErrors && customErrors[payload.code] != null) {
title = customErrors[payload.code].title;
text = customErrors[payload.code].text;
} else if (payload.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 (payload.code === 'RATE_LIMIT_EXCEEDED') {
title = i18n.ts.cannotPerformTemporary;
text = i18n.ts.cannotPerformTemporaryDescription;
} else if (payload.code === 'INVALID_PARAM') {
title = i18n.ts.invalidParamError;
text = i18n.ts.invalidParamErrorDescription;
} else if (payload.code === 'ROLE_PERMISSION_DENIED') {
title = i18n.ts.permissionDeniedError;
text = i18n.ts.permissionDeniedErrorDescription;
} else if (payload.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;
}
} else if (err.message.startsWith('Unexpected token')) {
title = i18n.ts.gotInvalidResponseError;
@ -119,13 +124,12 @@ export function apiWithDialog<
}
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,
T extends Promise<any>,
R = T extends Promise<infer R> ? R : never,
>(
promise: T,
onSuccess?: ((res: R) => void) | null,
onFailure?: ((err: E) => void) | null,
onFailure?: ((err: any) => void) | null,
text?: string,
): T {
const showing = ref(true);

View file

@ -1,11 +0,0 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
/** rejectに型付けができるPromise */
export class ErrPromise<TSuccess, TError> extends Promise<TSuccess> {
constructor(executor: (resolve: (value: TSuccess | PromiseLike<TSuccess>) => void, reject: (reason: TError) => void) => void) {
super(executor);
}
}

View file

@ -7,7 +7,6 @@ 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
@ -15,14 +14,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'],
ER 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,
): ErrPromise<_ResT, RE> {
): Promise<_ResT> {
if (endpoint.includes('://')) throw new Error('invalid endpoint');
pendingApiRequestsCount.value++;
@ -30,7 +29,7 @@ export function misskeyApi<
pendingApiRequestsCount.value--;
};
const promise = new ErrPromise<_ResT, RE>((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;
@ -53,9 +52,11 @@ export function misskeyApi<
} else if (res.status === 204) {
resolve(undefined as _ResT); // void -> undefined
} else {
reject(body.error);
reject(new Misskey.api.APIError<ER>(body.error));
}
}).catch(reject);
}).catch((reason) => {
reject(new Error(reason));
});
});
promise.then(onFinally, onFinally);
@ -68,12 +69,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'],
ER 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,
): ErrPromise<_ResT, RE> {
): Promise<_ResT> {
pendingApiRequestsCount.value++;
const onFinally = () => {
@ -82,7 +83,7 @@ export function misskeyApiGet<
const query = new URLSearchParams(data as any);
const promise = new ErrPromise<_ResT, RE>((resolve, reject) => {
const promise = new Promise<_ResT>((resolve, reject) => {
// Send request
window.fetch(`${apiUrl}/${endpoint}?${query}`, {
method: 'GET',
@ -96,9 +97,11 @@ export function misskeyApiGet<
} else if (res.status === 204) {
resolve(undefined as _ResT); // void -> undefined
} else {
reject(body.error);
reject(new Misskey.api.APIError<ER>(body.error));
}
}).catch(reject);
}).catch((reason) => {
reject(new Error(reason));
});
});
promise.then(onFinally, onFinally);