Skip to content

Commit

Permalink
feat: rest api implement
Browse files Browse the repository at this point in the history
  • Loading branch information
monkeyWie committed Sep 27, 2023
1 parent 0c94a83 commit dddaac1
Show file tree
Hide file tree
Showing 14 changed files with 402 additions and 305 deletions.
5 changes: 4 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
{
"ignorePatterns": ["node_modules/", "dist/"],
"ignorePatterns": [
"node_modules/",
"dist/"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 12,
Expand Down
3 changes: 2 additions & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 120,
"tabWidth": 2
"tabWidth": 2,
"endOfLine": "auto"
}
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Gopeed Javascript Monerepo

Gopeed development kit for javascript.

## Build

```bash
pnpm install
pnpm run build
```
17 changes: 13 additions & 4 deletions packages/rest/package.json → packages/gopeed-rest/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,26 @@
"name": "@gopeed/rest",
"version": "1.0.0",
"description": "",
"main": "dist/index.cjs.js",
"module": "dist/index.esm.js",
"main": "dist/index.js",
"exports": {
".": {
"require": "./dist/index.cjs",
"default": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"type": "module",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "tsc index.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@gopeed/model": "workspace:*"
"@gopeed/types": "workspace:*"
}
}
}
139 changes: 139 additions & 0 deletions packages/gopeed-rest/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { CreateTaskWithRequest, CreateTaskWithResolveResult, ResolveResult, Task, TaskStatus } from '@gopeed/types';

interface ClientOptions {
host: string;
token: string;
}

class ApiError extends Error {
code: number;
msg: string;

constructor(code: number, msg: string) {
super(msg);
this.code = code;
this.msg = msg;
}
}

class Client {
private options: ClientOptions;

constructor(options: ClientOptions = { host: 'http://127.0.0.1:9999', token: '' }) {
this.options = options;
}

/**
* Resolve the download request
* @param request
* @returns
*/
public async resole(request: Request): Promise<ResolveResult> {
return await this.doRequest<ResolveResult>('POST', '/api/v1/resolve', {
data: request,
});
}

/**
* Create a new download task
* @param request
* @returns
*/
public async createTask(request: CreateTaskWithResolveResult | CreateTaskWithRequest): Promise<string> {
return await this.doRequest<string>('POST', '/api/v1/tasks', {
data: request,
});
}

/**
* Get task list
* @param statuses
* @returns
*/
public async getTasks(statuses: TaskStatus[] = []): Promise<Task[]> {
return await this.doRequest<Task[]>('GET', '/api/v1/tasks', {
query: {
status: statuses.join(','),
},
});
}

/**
* Pause a task
* @param id
*/
public async pauseTask(id: string): Promise<void> {
return await this.doRequest('PUT', `/api/v1/tasks/${id}/pause`);
}

/**
* Continue a task
* @param id
*/
public async continueTask(id: string): Promise<void> {
return await this.doRequest('PUT', `/api/v1/tasks/${id}/continue`);
}

/**
* Pause all tasks
*/
public async pauseAllTasks(): Promise<void> {
return await this.doRequest('PUT', '/api/v1/tasks/pause');
}

/**
* Continue all tasks
*/
public async continueAllTasks(): Promise<void> {
return await this.doRequest('PUT', '/api/v1/tasks/continue');
}

/**
* Delete a task
* @param id
* @param force
*/
public async deleteTask(id: string, force = false): Promise<void> {
return await this.doRequest('DELETE', `/api/v1/tasks/${id}?force=${force}`);
}

private async doRequest<T>(
method: string,
path: string,
{ query, data }: { query?: object; data?: object } = {}
): Promise<T> {
let url = this.options.host + path;
if (query) {
const queryParams = Object.entries(query)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value as string)}`)
.join('&');
url += '?' + queryParams;
}
const headers: Record<string, string> = {
'Content-Type': 'application/json',
};
if (this.options.token) {
headers['X-Api-Token'] = this.options.token;
}
try {
const resp = await fetch(url, {
method: method,
headers: headers,
body: data ? JSON.stringify(data) : undefined,
});
if (resp.status !== 200) {
throw new ApiError(1000, await resp.text());
}
const result = await resp.json();
if (result.code !== 0) {
throw new ApiError(result.code, result.msg);
}
return result.data as T;
} catch (error) {
throw new ApiError(1000, (error as Error).message);
}
}
}

export { Client };
export default Client;
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
{
"name": "@gopeed/model",
"name": "@gopeed/types",
"version": "1.0.0",
"description": "",
"main": "dist/index.cjs.js",
"module": "dist/index.esm.js",
"main": "dist/index.js",
"exports": {
".": {
"require": "./dist/index.cjs",
"default": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"type": "module",
"types": "dist/index.d.ts",
"scripts": {
Expand Down
27 changes: 18 additions & 9 deletions packages/model/src/index.ts → packages/gopeed-types/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,26 @@ export interface HttpReqExtra {
body: string | undefined;
}

export interface HttpOptExtra {
export interface BtReqExtra {
/**
* Concurrent connections
* Tracker url list
*/
connections: number;
trackers: string[];
}

export interface BtOptExtra {
export interface HttpOptExtra {
/**
* Tracker url list
* Concurrent connections
*/
trackers: string[];
connections: number;
}

/**
* Download request
*/
export interface Request {
url: string;
extra: HttpReqExtra;
extra: HttpReqExtra | BtReqExtra;
}

export interface FileInfo {
Expand All @@ -44,7 +44,6 @@ export interface Resource {
name: string;
size: number;
range: boolean;
rootDir: string;
files: FileInfo[];
hash: string;
}
Expand All @@ -70,7 +69,7 @@ export interface Options {
* Select the index of the specified file, if not set, download all files
*/
selectFiles: number[];
extra: HttpOptExtra | BtOptExtra;
extra: HttpOptExtra;
}

export type TaskStatus = 'ready' | 'running' | 'pause' | 'wait' | 'error' | 'done';
Expand Down Expand Up @@ -109,3 +108,13 @@ export interface Task {
*/
createdAt: string;
}

export interface CreateTaskWithResolveResult {
id: string;
opts: Options;
}

export interface CreateTaskWithRequest {
req: Request;
opts: Options;
}
12 changes: 9 additions & 3 deletions packages/gopeed/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,14 @@
"name": "gopeed",
"version": "1.0.0",
"description": "",
"main": "dist/index.cjs.js",
"module": "dist/index.esm.js",
"main": "dist/index.js",
"exports": {
".": {
"require": "./dist/index.cjs",
"default": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"type": "module",
"types": "dist/index.d.ts",
"scripts": {
Expand All @@ -13,6 +19,6 @@
"author": "",
"license": "ISC",
"devDependencies": {
"@gopeed/model": "workspace:*"
"@gopeed/types": "workspace:*"
}
}
2 changes: 1 addition & 1 deletion packages/gopeed/src/extension/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Request, Resource } from '@gopeed/model';
import { Request, Resource } from '@gopeed/types';

interface OnResovleContext {
req: Request;
Expand Down
18 changes: 0 additions & 18 deletions packages/gopeed/src/extension/package.json

This file was deleted.

7 changes: 3 additions & 4 deletions packages/gopeed/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ interface Gopeed {
hooks: Hooks;
}

declare const gopeed: Gopeed;

export const { hooks } = gopeed;
export default gopeed;
declare global {
const gopeed: Gopeed;
}
Loading

0 comments on commit dddaac1

Please sign in to comment.