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);

View File

@ -728,7 +728,6 @@ type ApGetResponse = operations['ap___get']['responses']['200']['content']['appl
declare namespace api {
export {
isAPIError,
ErrPromise,
SwitchCaseResponseType,
APIError,
FetchLike,
@ -753,13 +752,25 @@ class APIClient {
}
// @public (undocumented)
type APIError = {
id: string;
code: string;
message: string;
kind: 'client' | 'server';
info: Record<string, any>;
};
class APIError<ER extends Endpoints[keyof Endpoints]['errors'] = {}> extends Error {
// (undocumented)
readonly [MK_API_ERROR] = true;
constructor(response: ER extends Record<string, never> ? {
id: string;
code: string;
message: string;
kind: 'client' | 'server';
info: Record<string, any>;
} : ER);
// (undocumented)
payload: ER extends Record<string, never> ? {
id: string;
code: string;
message: string;
kind: "client" | "server";
info: Record<string, any>;
} : ER;
}
// @public (undocumented)
type App = components['schemas']['App'];
@ -2708,11 +2719,6 @@ export { entities }
// @public (undocumented)
type Error_2 = components['schemas']['Error'];
// @public (undocumented)
class ErrPromise<TSuccess, TError> extends Promise<TSuccess> {
constructor(executor: (resolve: (value: TSuccess | PromiseLike<TSuccess>) => void, reject: (reason: TError) => void) => void);
}
// @public (undocumented)
type ExportCustomEmojisErrors = EndpointsErrors['export-custom-emojis'][keyof EndpointsErrors['export-custom-emojis']];
@ -3448,7 +3454,7 @@ type IRevokeTokenErrors = EndpointsErrors['i___revoke-token'][keyof EndpointsErr
type IRevokeTokenRequest = operations['i___revoke-token']['requestBody']['content']['application/json'];
// @public (undocumented)
function isAPIError(reason: Record<PropertyKey, unknown>): reason is APIError;
function isAPIError<ER extends Endpoints[keyof Endpoints]['errors']>(reason: any): reason is APIError<ER>;
// @public (undocumented)
type ISigninHistoryErrors = EndpointsErrors['i___signin-history'][keyof EndpointsErrors['i___signin-history']];

View File

@ -296,11 +296,11 @@ async function generateApiClientJSDoc(
' /**',
` * ${endpoint.description.split('\n').join('\n * ')}`,
' */',
` request<E extends '${endpoint.path}', P extends Endpoints[E][\'req\'], RE extends Endpoints[E][\'errors\']>(`,
` request<E extends '${endpoint.path}', P extends Endpoints[E][\'req\']>(`,
' endpoint: E,',
' params: P,',
' credential?: string | null,',
' ): ErrPromise<SwitchCaseResponseType<E, P>, RE>;',
' ): Promise<SwitchCaseResponseType<E, P>>;',
);
if (i < endpoints.length - 1) {

View File

@ -3,28 +3,31 @@ import './autogen/apiClientJSDoc.js';
import { SwitchCaseResponseType } from './api.types.js';
import type { Endpoints } from './api.types.js';
export class ErrPromise<TSuccess, TError> extends Promise<TSuccess> {
constructor(executor: (resolve: (value: TSuccess | PromiseLike<TSuccess>) => void, reject: (reason: TError) => void) => void) {
super(executor);
}
}
export type {
SwitchCaseResponseType,
} from './api.types.js';
const MK_API_ERROR = Symbol();
export type APIError = {
id: string;
code: string;
message: string;
kind: 'client' | 'server';
info: Record<string, any>;
};
export class APIError<ER extends Endpoints[keyof Endpoints]['errors'] = {}> extends Error {
export function isAPIError(reason: Record<PropertyKey, unknown>): reason is APIError {
return reason[MK_API_ERROR] === true;
public payload;
public readonly [MK_API_ERROR] = true;
constructor(response: ER extends Record<string, never> ? {
id: string;
code: string;
message: string;
kind: 'client' | 'server';
info: Record<string, any>;
} : ER) {
super('message' in response ? response.message : 'API Error');
this.payload = response;
}
}
export function isAPIError<ER extends Endpoints[keyof Endpoints]['errors']>(reason: any): reason is APIError<ER> {
return reason instanceof Error && MK_API_ERROR in reason;
}
export type FetchLike = (input: string, init?: {
@ -55,12 +58,13 @@ export class APIClient {
this.fetch = opts.fetch ?? ((...args) => fetch(...args));
}
public request<E extends keyof Endpoints, P extends Endpoints[E]['req'], RE extends Endpoints[E]['errors']>(
public request<E extends keyof Endpoints, P extends Endpoints[E]['req'], ER extends Endpoints[E]['errors']>(
endpoint: E,
params: P = {} as P,
credential?: string | null,
): ErrPromise<SwitchCaseResponseType<E, P>, RE> {
return new ErrPromise((resolve, reject) => {
): Promise<SwitchCaseResponseType<E, P>> {
return new Promise((resolve, reject) => {
this.fetch(`${this.origin}/api/${endpoint}`, {
method: 'POST',
body: JSON.stringify({
@ -78,12 +82,11 @@ export class APIClient {
if (res.status === 200 || res.status === 204) {
resolve(body);
} else {
reject({
[MK_API_ERROR]: true,
...body.error,
});
reject(new APIError<ER>(body.error));
}
}).catch(reject);
}).catch((reason) => {
reject(new Error(reason));
});
});
}
}

File diff suppressed because it is too large Load Diff

View File

@ -2271,6 +2271,7 @@ export type EndpointsErrors = {
'NO_SUCH_NOTE': IdentifiableError['033d0620-5bfe-4027-965d-980b0c85a3ea'],
'ALREADY_REACTED': IdentifiableError['71efcf98-86d6-4e2b-b2ad-9d032369366b'],
'YOU_HAVE_BEEN_BLOCKED': IdentifiableError['20ef5475-9f38-4e4c-bd33-de6d979498ec'],
'CANNOT_REACT_TO_RENOTE': IdentifiableError['eaccdc08-ddef-43fe-908f-d108faad57f5'],
'INVALID_PARAM': IdentifiableError['3d81ceae-475f-4600-b2a8-2bc116157532'],
'CREDENTIAL_REQUIRED': IdentifiableError['1384574d-a912-4b81-8601-c7b1c4085df1'],
'AUTHENTICATION_FAILED': IdentifiableError['b0a7f5f8-dc2f-4171-b91f-de88ad238e14'],
@ -3298,6 +3299,7 @@ export type IdentifiableError = {
'033d0620-5bfe-4027-965d-980b0c85a3ea': {'message':'No such note.', 'code':'NO_SUCH_NOTE', 'id':'033d0620-5bfe-4027-965d-980b0c85a3ea', [x: string]: any },
'71efcf98-86d6-4e2b-b2ad-9d032369366b': {'message':'You are already reacting to that note.', 'code':'ALREADY_REACTED', 'id':'71efcf98-86d6-4e2b-b2ad-9d032369366b', [x: string]: any },
'20ef5475-9f38-4e4c-bd33-de6d979498ec': {'message':'You cannot react this note because you have been blocked by this user.', 'code':'YOU_HAVE_BEEN_BLOCKED', 'id':'20ef5475-9f38-4e4c-bd33-de6d979498ec', [x: string]: any },
'eaccdc08-ddef-43fe-908f-d108faad57f5': {'message':'You cannot react to Renote.', 'code':'CANNOT_REACT_TO_RENOTE', 'id':'eaccdc08-ddef-43fe-908f-d108faad57f5', [x: string]: any },
'764d9fce-f9f2-4a0e-92b1-6ceac9a7ad37': {'message':'No such note.', 'code':'NO_SUCH_NOTE', 'id':'764d9fce-f9f2-4a0e-92b1-6ceac9a7ad37', [x: string]: any },
'92f4426d-4196-4125-aa5b-02943e2ec8fc': {'message':'You are not reacting to that note.', 'code':'NOT_REACTED', 'id':'92f4426d-4196-4125-aa5b-02943e2ec8fc', [x: string]: any },
'12908022-2e21-46cd-ba6a-3edaf6093f46': {'message':'No such note.', 'code':'NO_SUCH_NOTE', 'id':'12908022-2e21-46cd-ba6a-3edaf6093f46', [x: string]: any },