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

View File

@ -24,7 +24,6 @@ import MkContextMenu from '@/components/MkContextMenu.vue';
import { MenuItem } from '@/types/menu.js'; import { MenuItem } from '@/types/menu.js';
import copyToClipboard from '@/scripts/copy-to-clipboard.js'; import copyToClipboard from '@/scripts/copy-to-clipboard.js';
import { showMovedDialog } from '@/scripts/show-moved-dialog.js'; import { showMovedDialog } from '@/scripts/show-moved-dialog.js';
import { ErrPromise } from '@/scripts/err-promise.js';
export const openingWindowsCount = ref(0); export const openingWindowsCount = ref(0);
@ -43,7 +42,7 @@ export function apiWithDialog<
customErrors?: CustomErrorDef<ER>, customErrors?: CustomErrorDef<ER>,
) { ) {
const promise = misskeyApi(endpoint, data, token); const promise = misskeyApi(endpoint, data, token);
promiseDialog(promise, null, async (err) => { promiseDialog(promise, null, async (err: Error) => {
let title: string | undefined; let title: string | undefined;
let text: string; let text: string;
@ -51,57 +50,63 @@ export function apiWithDialog<
if ('message' in err && err.message != null) { if ('message' in err && err.message != null) {
initialText.push(err.message); initialText.push(err.message);
} }
if ('id' in err && err.id != null) { if (Misskey.api.isAPIError<ER>(err) && 'id' in err.payload && err.payload.id != null) {
initialText.push(err.id); initialText.push(err.payload.id);
} }
text = initialText.join('\n'); text = initialText.join('\n');
if ('code' in err && err.code != null) { if (Misskey.api.isAPIError<ER>(err)) {
if (customErrors && customErrors[err.code] != null) { const { payload } = err;
title = customErrors[err.code].title; if ('code' in payload && payload.code != null) {
text = customErrors[err.code].text; if (customErrors && customErrors[payload.code] != null) {
} else if (err.code === 'INTERNAL_ERROR') { title = customErrors[payload.code].title;
title = i18n.ts.internalServerError; text = customErrors[payload.code].text;
text = i18n.ts.internalServerErrorDescription; } else if (payload.code === 'INTERNAL_ERROR') {
const date = new Date().toISOString(); title = i18n.ts.internalServerError;
const { result } = await actions({ text = i18n.ts.internalServerErrorDescription;
type: 'error', const date = new Date().toISOString();
title, const { result } = await actions({
text, type: 'error',
actions: [{ title,
value: 'ok', text,
text: i18n.ts.gotIt, actions: [{
primary: true, value: 'ok',
}, { text: i18n.ts.gotIt,
value: 'copy', primary: true,
text: i18n.ts.copyErrorInfo, }, {
}], value: 'copy',
}); text: i18n.ts.copyErrorInfo,
if (result === 'copy') { }],
const text = [ });
`Endpoint: ${endpoint}`, if (result === 'copy') {
('info' in err) ? `Info: ${JSON.stringify(err.info)}` : undefined, const text = [
`Date: ${date}`, `Endpoint: ${endpoint}`,
].filter(x => x != null); ('info' in err) ? `Info: ${JSON.stringify(err.info)}` : undefined,
copyToClipboard(text.join('\n')); `Date: ${date}`,
success(); ].filter(x => x != null);
} copyToClipboard(text.join('\n'));
return; success();
} else if (err.code === 'RATE_LIMIT_EXCEEDED') { }
title = i18n.ts.cannotPerformTemporary; return;
text = i18n.ts.cannotPerformTemporaryDescription; } else if (payload.code === 'RATE_LIMIT_EXCEEDED') {
} else if (err.code === 'INVALID_PARAM') { title = i18n.ts.cannotPerformTemporary;
title = i18n.ts.invalidParamError; text = i18n.ts.cannotPerformTemporaryDescription;
text = i18n.ts.invalidParamErrorDescription; } else if (payload.code === 'INVALID_PARAM') {
} else if (err.code === 'ROLE_PERMISSION_DENIED') { title = i18n.ts.invalidParamError;
title = i18n.ts.permissionDeniedError; text = i18n.ts.invalidParamErrorDescription;
text = i18n.ts.permissionDeniedErrorDescription; } else if (payload.code === 'ROLE_PERMISSION_DENIED') {
} else if (err.code.startsWith('TOO_MANY')) { title = i18n.ts.permissionDeniedError;
title = i18n.ts.youCannotCreateAnymore; text = i18n.ts.permissionDeniedErrorDescription;
if ('id' in err && err.id != null) { } else if (payload.code.startsWith('TOO_MANY')) {
text = `${i18n.ts.error}: ${err.id}`; title = i18n.ts.youCannotCreateAnymore;
} else { if ('id' in err && err.id != null) {
text = `${i18n.ts.error}`; 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')) { } else if (err.message.startsWith('Unexpected token')) {
title = i18n.ts.gotInvalidResponseError; title = i18n.ts.gotInvalidResponseError;
@ -119,13 +124,12 @@ export function apiWithDialog<
} }
export function promiseDialog< export function promiseDialog<
T extends ErrPromise<any, any> | Promise<any>, T extends Promise<any>,
R = T extends ErrPromise<infer R, unknown> ? R : T extends Promise<infer R> ? R : never, R = T extends Promise<infer R> ? R : never,
E = T extends ErrPromise<unknown, infer E> ? E : T extends Promise<unknown> ? any : never,
>( >(
promise: T, promise: T,
onSuccess?: ((res: R) => void) | null, onSuccess?: ((res: R) => void) | null,
onFailure?: ((err: E) => void) | null, onFailure?: ((err: any) => void) | null,
text?: string, text?: string,
): T { ): T {
const showing = ref(true); 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 { ref } from 'vue';
import { apiUrl } from '@/config.js'; import { apiUrl } from '@/config.js';
import { $i } from '@/account.js'; import { $i } from '@/account.js';
import { ErrPromise } from '@/scripts/err-promise.js';
export const pendingApiRequestsCount = ref(0); export const pendingApiRequestsCount = ref(0);
// Implements Misskey.api.ApiClient.request // Implements Misskey.api.ApiClient.request
@ -15,14 +14,14 @@ export function misskeyApi<
ResT = void, ResT = void,
E extends keyof Misskey.Endpoints = keyof Misskey.Endpoints, E extends keyof Misskey.Endpoints = keyof Misskey.Endpoints,
P extends Misskey.Endpoints[E]['req'] = Misskey.Endpoints[E]['req'], 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, _ResT = ResT extends void ? Misskey.api.SwitchCaseResponseType<E, P> : ResT,
>( >(
endpoint: E, endpoint: E,
data: P = {} as any, data: P = {} as any,
token?: string | null | undefined, token?: string | null | undefined,
signal?: AbortSignal, signal?: AbortSignal,
): ErrPromise<_ResT, RE> { ): Promise<_ResT> {
if (endpoint.includes('://')) throw new Error('invalid endpoint'); if (endpoint.includes('://')) throw new Error('invalid endpoint');
pendingApiRequestsCount.value++; pendingApiRequestsCount.value++;
@ -30,7 +29,7 @@ export function misskeyApi<
pendingApiRequestsCount.value--; pendingApiRequestsCount.value--;
}; };
const promise = new ErrPromise<_ResT, RE>((resolve, reject) => { const promise = new Promise<_ResT>((resolve, reject) => {
// Append a credential // Append a credential
if ($i) (data as any).i = $i.token; if ($i) (data as any).i = $i.token;
if (token !== undefined) (data as any).i = token; if (token !== undefined) (data as any).i = token;
@ -53,9 +52,11 @@ export function misskeyApi<
} else if (res.status === 204) { } else if (res.status === 204) {
resolve(undefined as _ResT); // void -> undefined resolve(undefined as _ResT); // void -> undefined
} else { } else {
reject(body.error); reject(new Misskey.api.APIError<ER>(body.error));
} }
}).catch(reject); }).catch((reason) => {
reject(new Error(reason));
});
}); });
promise.then(onFinally, onFinally); promise.then(onFinally, onFinally);
@ -68,12 +69,12 @@ export function misskeyApiGet<
ResT = void, ResT = void,
E extends keyof Misskey.Endpoints = keyof Misskey.Endpoints, E extends keyof Misskey.Endpoints = keyof Misskey.Endpoints,
P extends Misskey.Endpoints[E]['req'] = Misskey.Endpoints[E]['req'], 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, _ResT = ResT extends void ? Misskey.api.SwitchCaseResponseType<E, P> : ResT,
>( >(
endpoint: E, endpoint: E,
data: P = {} as any, data: P = {} as any,
): ErrPromise<_ResT, RE> { ): Promise<_ResT> {
pendingApiRequestsCount.value++; pendingApiRequestsCount.value++;
const onFinally = () => { const onFinally = () => {
@ -82,7 +83,7 @@ export function misskeyApiGet<
const query = new URLSearchParams(data as any); const query = new URLSearchParams(data as any);
const promise = new ErrPromise<_ResT, RE>((resolve, reject) => { const promise = new Promise<_ResT>((resolve, reject) => {
// Send request // Send request
window.fetch(`${apiUrl}/${endpoint}?${query}`, { window.fetch(`${apiUrl}/${endpoint}?${query}`, {
method: 'GET', method: 'GET',
@ -96,9 +97,11 @@ export function misskeyApiGet<
} else if (res.status === 204) { } else if (res.status === 204) {
resolve(undefined as _ResT); // void -> undefined resolve(undefined as _ResT); // void -> undefined
} else { } else {
reject(body.error); reject(new Misskey.api.APIError<ER>(body.error));
} }
}).catch(reject); }).catch((reason) => {
reject(new Error(reason));
});
}); });
promise.then(onFinally, onFinally); promise.then(onFinally, onFinally);

View File

@ -728,7 +728,6 @@ type ApGetResponse = operations['ap___get']['responses']['200']['content']['appl
declare namespace api { declare namespace api {
export { export {
isAPIError, isAPIError,
ErrPromise,
SwitchCaseResponseType, SwitchCaseResponseType,
APIError, APIError,
FetchLike, FetchLike,
@ -753,13 +752,25 @@ class APIClient {
} }
// @public (undocumented) // @public (undocumented)
type APIError = { class APIError<ER extends Endpoints[keyof Endpoints]['errors'] = {}> extends Error {
id: string; // (undocumented)
code: string; readonly [MK_API_ERROR] = true;
message: string; constructor(response: ER extends Record<string, never> ? {
kind: 'client' | 'server'; id: string;
info: Record<string, any>; 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) // @public (undocumented)
type App = components['schemas']['App']; type App = components['schemas']['App'];
@ -2708,11 +2719,6 @@ export { entities }
// @public (undocumented) // @public (undocumented)
type Error_2 = components['schemas']['Error']; 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) // @public (undocumented)
type ExportCustomEmojisErrors = EndpointsErrors['export-custom-emojis'][keyof EndpointsErrors['export-custom-emojis']]; 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']; type IRevokeTokenRequest = operations['i___revoke-token']['requestBody']['content']['application/json'];
// @public (undocumented) // @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) // @public (undocumented)
type ISigninHistoryErrors = EndpointsErrors['i___signin-history'][keyof EndpointsErrors['i___signin-history']]; 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 * ')}`, ` * ${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,', ' endpoint: E,',
' params: P,', ' params: P,',
' credential?: string | null,', ' credential?: string | null,',
' ): ErrPromise<SwitchCaseResponseType<E, P>, RE>;', ' ): Promise<SwitchCaseResponseType<E, P>>;',
); );
if (i < endpoints.length - 1) { if (i < endpoints.length - 1) {

View File

@ -3,28 +3,31 @@ import './autogen/apiClientJSDoc.js';
import { SwitchCaseResponseType } from './api.types.js'; import { SwitchCaseResponseType } from './api.types.js';
import type { Endpoints } 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 { export type {
SwitchCaseResponseType, SwitchCaseResponseType,
} from './api.types.js'; } from './api.types.js';
const MK_API_ERROR = Symbol(); const MK_API_ERROR = Symbol();
export type APIError = { export class APIError<ER extends Endpoints[keyof Endpoints]['errors'] = {}> extends Error {
id: string;
code: string;
message: string;
kind: 'client' | 'server';
info: Record<string, any>;
};
export function isAPIError(reason: Record<PropertyKey, unknown>): reason is APIError { public payload;
return reason[MK_API_ERROR] === true; 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?: { export type FetchLike = (input: string, init?: {
@ -55,12 +58,13 @@ export class APIClient {
this.fetch = opts.fetch ?? ((...args) => fetch(...args)); 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, endpoint: E,
params: P = {} as P, params: P = {} as P,
credential?: string | null, credential?: string | null,
): ErrPromise<SwitchCaseResponseType<E, P>, RE> { ): Promise<SwitchCaseResponseType<E, P>> {
return new ErrPromise((resolve, reject) => { return new Promise((resolve, reject) => {
this.fetch(`${this.origin}/api/${endpoint}`, { this.fetch(`${this.origin}/api/${endpoint}`, {
method: 'POST', method: 'POST',
body: JSON.stringify({ body: JSON.stringify({
@ -78,12 +82,11 @@ export class APIClient {
if (res.status === 200 || res.status === 204) { if (res.status === 200 || res.status === 204) {
resolve(body); resolve(body);
} else { } else {
reject({ reject(new APIError<ER>(body.error));
[MK_API_ERROR]: true,
...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'], 'NO_SUCH_NOTE': IdentifiableError['033d0620-5bfe-4027-965d-980b0c85a3ea'],
'ALREADY_REACTED': IdentifiableError['71efcf98-86d6-4e2b-b2ad-9d032369366b'], 'ALREADY_REACTED': IdentifiableError['71efcf98-86d6-4e2b-b2ad-9d032369366b'],
'YOU_HAVE_BEEN_BLOCKED': IdentifiableError['20ef5475-9f38-4e4c-bd33-de6d979498ec'], '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'], 'INVALID_PARAM': IdentifiableError['3d81ceae-475f-4600-b2a8-2bc116157532'],
'CREDENTIAL_REQUIRED': IdentifiableError['1384574d-a912-4b81-8601-c7b1c4085df1'], 'CREDENTIAL_REQUIRED': IdentifiableError['1384574d-a912-4b81-8601-c7b1c4085df1'],
'AUTHENTICATION_FAILED': IdentifiableError['b0a7f5f8-dc2f-4171-b91f-de88ad238e14'], '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 }, '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 }, '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 }, '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 }, '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 }, '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 }, '12908022-2e21-46cd-ba6a-3edaf6093f46': {'message':'No such note.', 'code':'NO_SUCH_NOTE', 'id':'12908022-2e21-46cd-ba6a-3edaf6093f46', [x: string]: any },