Skip to content

Commit

Permalink
Implement custom download API and related functionality for markdown …
Browse files Browse the repository at this point in the history
…files
  • Loading branch information
trheyi committed Nov 5, 2024
1 parent 46da884 commit 05734fd
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 4 deletions.
11 changes: 10 additions & 1 deletion .types/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,9 @@ export class FS {
ReadDir(path: string, recursive: boolean = false): string[] {
return [];
}

Download(path: string): { content: ReadCloser; type: MimeType } {
return { content: 0, type: "" };
}
Zip(source: string, destination: string) {}
MkdirAll(path: string) {}
DirName(path: string): string {
Expand Down Expand Up @@ -158,6 +160,9 @@ export class FS {
MoveAppend(source: string, destination: string) {}
Remove(path: string) {}
RemoveAll(path: string) {}
MimeType(name: string): string {
return "";
}
}

export const http = {
Expand Down Expand Up @@ -344,3 +349,7 @@ export type UploadFileResponse =
*/
[key: string]: any;
};

type ReadCloser = number;

type MimeType = string;
18 changes: 18 additions & 0 deletions apis/download.http.yao
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "Custom Download",
"version": "1.0.0",
"guard": "-",
"paths": [
{
"path": "/*name",
"method": "GET",
"process": "scripts.download.Markdown",
"in": ["$param.name"],
"out": {
"status": 200,
"headers": { "Content-Type": "{{ type }}" },
"body": "{{ content }}"
}
}
]
}
23 changes: 23 additions & 0 deletions scripts/download.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Exception, FS } from "@yao/runtime";

/**
* Download markdown file by name
* yao run scripts.download.Markdown README.md
* curl -vv http://localhost:5099/api/download/README.md
* @param name
*/
function Markdown(name: string) {
const fs = new FS(`app`); // app is the application root directory
// const fs = new FS("data"); // data is the application data directory
const filename = `${name}`;
const ext = fs.ExtName(filename);
if (ext !== "md") {
throw new Exception(`File is not markdown: ${filename}`, 400);
}

if (!fs.Exists(filename)) {
throw new Exception(`File not found: ${filename}`, 404);
}

return fs.Download(filename);
}
7 changes: 4 additions & 3 deletions tables/hero.tab.yao
Original file line number Diff line number Diff line change
Expand Up @@ -275,9 +275,10 @@
"bind": "title",
"view": {
"type": "A",
"props": {
"href": "http://localhost:8000/yao/x/Form/hero/1/edit"
}
// You can also use the following configuration to customize the download API logic
// api: /apis/download.http.yao
// process: /scripts/download.ts
"props": { "href": "/api/download/README.md?from={{ id }}" }
}
},
"角色(数值)": {
Expand Down

0 comments on commit 05734fd

Please sign in to comment.