@geektech/backone-cli
项目模板
minimal / rest-api / websocket 三种项目模板详解。
CLI 内置三种项目模板,均生成 package.json / tsconfig.json / src/index.ts / README.md / .gitignore,并依赖 @geektech/backone。
模板一览
| 模板 | 描述 | 生成内容 |
|---|---|---|
minimal | 最小骨架:单路由,零额外内容 | src/index.ts:createServer + 一个 GET 路由 |
rest-api | REST API:路由组 + 中间件 + CRUD 示例 | 内存用户表 + GET/POST/DELETE 接口 |
websocket | WebSocket 实时聊天 + 浏览器客户端 | /chat 广播 + public/index.html 聊天 UI |
minimal
最小骨架,适合作为新项目起点:
ts
import { createServer } from '@geektech/backone';
const app = createServer({ port: 3000 });
app.get('/', () => 'Hello, BackOne!');
const port = await app.listen();
console.log(`Server running at http://127.0.0.1:${port}`);rest-api
REST API 模板演示路由组、路径参数、请求体与 HttpError 的完整用法:
ts
import { createServer, HttpError } from '@geektech/backone';
const app = createServer({ port: 3000, development: true });
app.useLogger();
app.useCors();
app.group('/api', (api) => {
api.get('/users', () => users);
api.get<{ id: string }>('/users/:id', (ctx) => {
const user = users.find((u) => u.id === Number(ctx.params.id));
if (!user) throw new HttpError(404, 'User not found');
return user;
});
api.post('/users', async (ctx) => {
const body = await ctx.bodyJson<{ name: string; email: string }>();
const user = { id: nextId++, ...body };
users.push(user);
return ctx.json(user, 201);
});
api.delete<{ id: string }>('/users/:id', (ctx) => {
const idx = users.findIndex((u) => u.id === Number(ctx.params.id));
if (idx === -1) throw new HttpError(404, 'User not found');
users.splice(idx, 1);
return ctx.noContent();
});
});websocket
WebSocket 模板包含服务端广播与浏览器聊天 UI(public/index.html,由 serveStatic 托管):
ts
import { createServer } from '@geektech/backone';
import type { BackOneWebSocket } from '@geektech/backone';
const app = createServer({ port: 3000, development: true });
app.serveStatic('/', './public');
const clients = new Set<BackOneWebSocket>();
app.ws('/chat', {
open(ws) { clients.add(ws); broadcast(`System: joined (${clients.size} online)`); },
message(_ws, message) { broadcast(`User: ${String(message)}`); },
close(ws) { clients.delete(ws); broadcast(`System: left (${clients.size} online)`); },
});
function broadcast(message: string) {
for (const client of clients) client.send(message);
}提示
打开多个浏览器标签页访问 http://127.0.0.1:3000 即可体验实时聊天。