@@ -6,7 +6,12 @@ import type {
66 NotLoggedInError ,
77 NotPrivilegeError ,
88} from "../deps/scrapbox.ts" ;
9- import { cookie , getCSRFToken } from "./utils.ts" ;
9+ import {
10+ cookie ,
11+ getCSRFToken ,
12+ makeCustomError ,
13+ tryToErrorLike ,
14+ } from "./utils.ts" ;
1015import type { Result } from "./utils.ts" ;
1116
1217/** `importPages`の認証情報 */
@@ -49,8 +54,9 @@ export async function importPages(
4954 csrf = result . csrfToken ;
5055 }
5156
57+ const path = `https://scrapbox.io/api/page-data/import/${ project } .json` ;
5258 const res = await fetch (
53- `https://scrapbox.io/api/page-data/import/ ${ project } .json` ,
59+ path ,
5460 {
5561 method : "POST" ,
5662 headers : {
@@ -64,12 +70,15 @@ export async function importPages(
6470
6571 if ( ! res . ok ) {
6672 if ( res . status === 503 ) {
67- const error = new Error ( ) ;
68- error . name = "ServerError" ;
69- error . message = "503 Service Unavailable" ;
70- throw error ;
73+ throw makeCustomError ( "ServerError" , "503 Service Unavailable" ) ;
74+ }
75+ const error = tryToErrorLike ( await res . text ( ) ) ;
76+ if ( ! error ) {
77+ throw makeCustomError (
78+ "UnexpectedError" ,
79+ `Unexpected error has occuerd when fetching "${ path } "` ,
80+ ) ;
7181 }
72- const error = ( await res . json ( ) ) as ErrorLike ;
7382 return { ok : false , ...error } ;
7483 }
7584 const result = ( await res . json ( ) ) as { message : string } ;
@@ -94,8 +103,10 @@ export async function exportPages<withMetadata extends true | false>(
94103 NotFoundError | NotPrivilegeError | NotLoggedInError
95104 >
96105> {
106+ const path =
107+ `https://scrapbox.io/api/page-data/export/${ project } .json?metadata=${ metadata } ` ;
97108 const res = await fetch (
98- `https://scrapbox.io/api/page-data/export/ ${ project } .json?metadata= ${ metadata } ` ,
109+ path ,
99110 {
100111 headers : {
101112 Cookie : cookie ( sid ) ,
@@ -104,12 +115,22 @@ export async function exportPages<withMetadata extends true | false>(
104115 ) ;
105116
106117 if ( ! res . ok ) {
107- const error = ( await res . json ( ) ) as
108- | NotFoundError
109- | NotPrivilegeError
110- | NotLoggedInError ;
118+ const error = ( await res . json ( ) ) ;
111119 return { ok : false , ...error } ;
112120 }
121+ if ( ! res . ok ) {
122+ const error = tryToErrorLike ( await res . text ( ) ) ;
123+ if ( ! error ) {
124+ throw makeCustomError (
125+ "UnexpectedError" ,
126+ `Unexpected error has occuerd when fetching "${ path } "` ,
127+ ) ;
128+ }
129+ return {
130+ ok : false ,
131+ ...( error as NotFoundError | NotPrivilegeError | NotLoggedInError ) ,
132+ } ;
133+ }
113134 const result = ( await res . json ( ) ) as ExportedData < withMetadata > ;
114135 return { ok : true , ...result } ;
115136}
0 commit comments