From 9cd59d91460fe032daf1be4d77fdc6e1e8e9e94d Mon Sep 17 00:00:00 2001 From: Himself65 Date: Wed, 29 Mar 2023 13:42:55 -0500 Subject: [PATCH] test: throw no permission when download failed (#1742) --- .../src/affine/__tests__/api.spec.ts | 25 ++++++++++--------- packages/workspace/src/affine/api/index.ts | 11 ++++++++ 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/packages/workspace/src/affine/__tests__/api.spec.ts b/packages/workspace/src/affine/__tests__/api.spec.ts index 4f0f6b8ebd..55ffc1a2bb 100644 --- a/packages/workspace/src/affine/__tests__/api.spec.ts +++ b/packages/workspace/src/affine/__tests__/api.spec.ts @@ -101,19 +101,20 @@ describe('api', () => { document.removeEventListener('affine-error', listener); }); - test('blob too large', async () => { - let called = false; - try { - await workspaceApis.uploadBlob( - 'test', - new ArrayBuffer(1024 * 1024 * 1024 + 1), - 'image/png' - ); - } catch (e) { - called = true; + test('no permission', async () => { + await workspaceApis.downloadWorkspace('not-exist').catch(e => { expect(e).toBeInstanceOf(RequestError); - } - expect(called, 'throw error').toBe(true); + expect(e.code).toBe(MessageCode.noPermission); + }); + }); + + test('blob too large', async () => { + await workspaceApis + .uploadBlob('test', new ArrayBuffer(1024 * 1024 * 1024 + 1), 'image/png') + .catch(e => { + expect(e).toBeInstanceOf(RequestError); + expect(e.code).toBe(MessageCode.blobTooLarge); + }); }); test('refresh token', async () => { diff --git a/packages/workspace/src/affine/api/index.ts b/packages/workspace/src/affine/api/index.ts index 1680f9f647..1c8437e2ff 100644 --- a/packages/workspace/src/affine/api/index.ts +++ b/packages/workspace/src/affine/api/index.ts @@ -5,9 +5,12 @@ import { z } from 'zod'; import { getLoginStorage } from '../login'; export class RequestError extends Error { + public readonly code: MessageCode; + constructor(code: MessageCode, cause: unknown | null = null) { super(Messages[code].message); sendMessage(code); + this.code = code; this.name = 'RequestError'; this.cause = cause; } @@ -360,8 +363,16 @@ export function createWorkspaceApis(prefixUrl = '/') { Authorization: auth.token, }, }) + .then(r => + r.status === 403 + ? Promise.reject(new RequestError(MessageCode.noPermission)) + : r + ) .then(r => r.arrayBuffer()) .catch(e => { + if (e instanceof RequestError) { + throw e; + } throw new RequestError(MessageCode.downloadWorkspaceFailed, e); }); }