Skip to content

refactor(rest): redesign REST API to use ScrapboxResponse #216

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 72 additions & 36 deletions browser/websocket/pull.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
import {
createErr,
createOk,
isErr,
mapForResult,
type Result,
unwrapOk,
} from "option-t/plain_result";
import type {
GuestUser,
MemberUser,
NotFoundError,
NotLoggedInError,
NotMemberError,
Page,
} from "@cosense/types/rest";
import {
createErrorResponse,
createSuccessResponse,
} from "../../rest/utils.ts";
import {
getPage,
type GetPageOption,
type TooLongURIError,
} from "../../rest/pages.ts";
import { getProfile } from "../../rest/profile.ts";
import { getProject } from "../../rest/project.ts";
import type { HTTPError } from "../../rest/responseIntoResult.ts";
import type { HTTPError } from "../../rest/errors.ts";
import type { AbortError, NetworkError } from "../../rest/robustFetch.ts";
import type { BaseOptions } from "../../rest/options.ts";
import type { TargetedResponse } from "../../rest/targeted_response.ts";

export interface PushMetadata extends Page {
projectId: string;
Expand All @@ -42,42 +41,70 @@ export const pull = async (
project: string,
title: string,
options?: GetPageOption,
): Promise<Result<PushMetadata, PullError>> => {
): Promise<
TargetedResponse<200 | 400 | 404 | 408 | 500, PushMetadata | PullError>
> => {
const [pageRes, userRes, projectRes] = await Promise.all([
getPage(project, title, options),
getUserId(options),
getProjectId(project, options),
]);
if (isErr(pageRes)) return pageRes;
if (isErr(userRes)) return userRes;
if (isErr(projectRes)) return projectRes;
return createOk({
...unwrapOk(pageRes),
projectId: unwrapOk(projectRes),
userId: unwrapOk(userRes),
});

if (!pageRes.ok || !userRes.ok || !projectRes.ok) {
const status = pageRes.ok
? (userRes.ok ? projectRes.status : userRes.status)
: pageRes.status;
const errorStatus = status === 404
? 404
: (status === 408 ? 408 : (status === 500 ? 500 : 400));
return createErrorResponse(errorStatus, {
message: "Failed to fetch required data",
} as PullError);
}

const page = await pageRes.json() as Page;
const userId = await userRes.clone().text();
const projectId = await projectRes.clone().text();

const metadata: PushMetadata = {
...page,
projectId,
userId,
};
return createSuccessResponse(metadata);
};
// TODO: 編集不可なページはStream購読だけ提供する

/** cached user ID */
let userId: string | undefined;
const getUserId = async (init?: BaseOptions): Promise<
Result<
string,
Omit<NotLoggedInError, "details"> | NetworkError | AbortError | HTTPError
TargetedResponse<
200 | 400 | 404 | 408 | 500,
| string
| Omit<NotLoggedInError, "details">
| NetworkError
| AbortError
| HTTPError
>
> => {
if (userId) return createOk(userId);
if (userId) {
return createSuccessResponse(userId);
}

const result = await getProfile(init);
if (isErr(result)) return result;
if (!result.ok) {
return createErrorResponse(400, {
name: "NotLoggedInError",
message: "Failed to fetch profile",
});
}

const user = unwrapOk(result);
const user = await result.json() as MemberUser | GuestUser;
if ("id" in user) {
userId = user.id;
return createOk(user.id);
return createSuccessResponse(user.id);
}
return createErr({
return createErrorResponse(400, {
name: "NotLoggedInError",
message: "This script cannot be used without login",
});
Expand All @@ -89,8 +116,9 @@ export const getProjectId = async (
project: string,
options?: BaseOptions,
): Promise<
Result<
string,
TargetedResponse<
200 | 400 | 404 | 408 | 500,
| string
| NotFoundError
| NotLoggedInError
| NotMemberError
Expand All @@ -100,13 +128,21 @@ export const getProjectId = async (
>
> => {
const cachedId = projectMap.get(project);
if (cachedId) return createOk(cachedId);
if (cachedId) {
return createSuccessResponse(cachedId);
}

const result = await getProject(project, options);
if (!result.ok) {
return createErrorResponse(404, {
name: "NotFoundError",
message: `Project ${project} not found`,
project,
});
}

return mapForResult(
await getProject(project, options),
({ id }) => {
projectMap.set(project, id);
return id;
},
);
const data = await result.json();
const id = (data as { id: string }).id;
projectMap.set(project, id);
return createSuccessResponse(id);
};
14 changes: 10 additions & 4 deletions browser/websocket/push.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,11 @@ export const push = async (
}
const socket = unwrapOk(result);
const pullResult = await pull(project, title);
if (isErr(pullResult)) return pullResult;
let metadata = unwrapOk(pullResult);
if (!pullResult.ok) {
const error = await pullResult.json() as PushError;
return createErr(error);
}
let metadata = await pullResult.json() as PushMetadata;

try {
let attempts = 0;
Expand Down Expand Up @@ -167,8 +170,11 @@ export const push = async (
if (name === "NotFastForwardError") {
await delay(1000);
const pullResult = await pull(project, title);
if (isErr(pullResult)) return pullResult;
metadata = unwrapOk(pullResult);
if (!pullResult.ok) {
const error = await pullResult.json() as PushError;
return createErr(error);
}
metadata = await pullResult.json() as PushMetadata;
}
reason = name;
// go back to the diff loop
Expand Down
1 change: 1 addition & 0 deletions deno.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"@std/async": "jsr:@std/async@1",
"@std/encoding": "jsr:@std/encoding@1",
"@std/json": "jsr:@std/json@^1.0.0",
"@std/testing": "jsr:@std/testing@^1.0.8",
"@std/testing/snapshot": "jsr:@std/testing@1/snapshot",
"@takker/md5": "jsr:@takker/md5@0.1",
"@takker/onp": "./vendor/raw.githubusercontent.com/takker99/onp/0.0.1/mod.ts",
Expand Down
131 changes: 66 additions & 65 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading