import { scheduleJob } from 'node-schedule'; // 定时任务 function setupScheduledTasks() { // 每6秒执行一次 setInterval(() => { taskEverySixSeconds(); }, 6000); // 每33分钟执行一次 setInterval(() => { taskEveryThirtyThreeMinutes(); }, 33 * 60 * 1000); // 每天的1点到5点之间执行 scheduleJob('0 * 1-5 * * *', taskEarlyMorning); } // 示例任务函数 function taskEverySixSeconds() { console.log('Running task every 6 seconds'); } function taskEveryThirtyThreeMinutes() { console.log('Running task every 33 minutes'); } function taskEarlyMorning() { console.log('Running early morning task'); } // 在main函数中调用 setupScheduledTasks();
app.all('/*', (req, res) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); if (req.method === 'OPTIONS') { res.status(204).end(); } else { res.next(); } });
import { verifyToken } from './auth'; // 假设你有一个auth模块来处理token验证 app.use(json(), (req, res, next) => { const token = req.header('Authorization')?.replace('Bearer ', ''); if (token) { try { const userInfo = verifyToken(token); // verifyToken应该返回用户信息或抛出错误 req.userInfo = userInfo; // 将用户信息写入请求对象 next(); } catch (error) { res.status(401).json({ error: 'Invalid token' }); } } else { res.status(401).json({ error: 'No token provided' }); } });
npm install node-schedule npm install cors
在这个示例中,我使用了cors
中间件来处理跨域请求,而不是手动设置CORS头。这是一个更简洁的方法,因为它会自动处理预请求(preflight)和其他CORS相关的复杂性。
确保你已经定义了taskEverySixSeconds
,taskEveryThirtyThreeMinutes
,和taskEarlyMorning
函数,它们将包含你的业务逻辑。
同时,verifyToken
函数应该是你在一个单独的文件中定义的,比如auth.ts
,它接受一个token,验证它,并返回用户信息或抛出错误。这里的中间件会检查请求头中的Authorization
字段,并尝试解析和验证token。如果验证成功,用户信息将被附加到req.userInfo
。
import { serve } from 'hyperexpress'; import { connectToDatabase } from './db'; import { setupRoutes } from './routes'; import { json } from 'hyperexpress'; import { setInterval } from 'timers'; import schedule from 'node-schedule'; import cors from 'cors'; const app = serve(); // 跨域处理 app.use(cors({ origin: '*', // 或者配置具体的允许域名 methods: 'GET, POST, PUT, DELETE', allowedHeaders: 'Content-Type, Authorization' })); app.use(json()); // Token验证中间件 app.use((req, res, next) => { const token = req.headers.authorization?.split(' ')[1]; // 获取Bearer后面的Token if (token) { try { const userInfo = verifyToken(token); // 假设verifyToken是一个解析Token并返回用户信息的函数 req.userInfo = userInfo; // 将用户信息写入请求对象 next(); } catch (error) { res.status(401).json({ error: 'Invalid token' }); } } else { next(); // 如果没有Token,可以选择继续或者返回错误 } }); // 设置路由 setupRoutes(app); // 定时任务 function setupScheduledTasks() { // 每6秒执行一次 setInterval(() => { taskEverySixSeconds(); }, 6000); // 每33分钟执行一次 setInterval(() => { taskEveryThirtyThreeMinutes(); }, 33 * 60 * 1000); // 每天的1点到5点之间执行 const rule = new schedule.RecurrenceRule(); rule.hour = [1, 5]; // 每天的1点到5点 rule.minute = 0; // 每小时的开始 schedule.scheduleJob(rule, taskEarlyMorning); } // 示例任务函数 function taskEverySixSeconds() { console.log('Running task every 6 seconds'); // 你的业务逻辑 } function taskEveryThirtyThreeMinutes() { console.log('Running task every 33 minutes'); // 你的业务逻辑 } function taskEarlyMorning() { console.log('Running early morning task'); // 你的业务逻辑 } async function main() { await connectToDatabase(); setupScheduledTasks(); // 设置定时任务 await app.listen(3000); console.log('Server is running on port 3000'); } main();
npm install hyperexpress @deepkit/orm @deepkit/orm-postgres-driver pg // src/entity/User.ts import { Entity, PrimaryKey, Property } from '@deepkit/orm'; @Entity() export class User { @PrimaryKey() id: number; @Property() name: string; @Property() email: string; }
// src/db.ts import { DeepKitConnection } from '@deepkit/orm'; import { User } from './entity/User'; export const connection = new DeepKitConnection({ type: 'postgres', host: 'localhost', port: 5432, username: 'your_username', password: 'your_password', database: 'your_database', entities: [User], }); export async function connectToDatabase() { await connection.connect(); }
4. 创建服务
创建用户服务来处理业务逻辑:
// src/service/UserService.ts import { Repository } from '@deepkit/orm'; import { User } from '../entity/User'; export class UserService { userRepository: Repository<User>; constructor() { this.userRepository = connection.getRepository(User); } async createUser(userData: Partial<User>): Promise<User> { const user = this.userRepository.create(userData); await this.userRepository.persistAndFlush(user); return user; } async findAllUsers(): Promise<User[]> { return this.userRepository.find(); } async findUserById(id: number): Promise<User | null> { return this.userRepository.findOne({ id }); } async updateUser(id: number, updatedData: Partial<User>): Promise<User | null> { await this.userRepository.update(id, updatedData); return this.userRepository.findOne({ id }); } async deleteUser(id: number): Promise<void> { await this.userRepository.removeAndFlush({ id }); } }
// src/main.ts import { serve } from 'hyperexpress'; import { connectToDatabase } from './db'; import { setupRoutes } from './routes'; import { json } from 'hyperexpress'; const app = serve(); app.use(json()); // Set up routes setupRoutes(app); async function main() { await connectToDatabase(); await app.listen(3000); console.log('Server is running on port 3000'); } main();
// src/routes.ts import { app } from './app'; import { UserService } from './service/UserService'; import { json } from 'hyperexpress'; // Helper function to set up all routes export function setupRoutes(app: ReturnType<typeof serve>) { const userService = new UserService(); app.post('/users', async (req, res) => { try { const user = await userService.createUser(req.body); res.status(201).json(user); } catch (error) { res.status(500).json({ error: error.message }); } }); // ... Other route handlers // Add the rest of the route handlers here // ... app.get('/users', async (req, res) => { // ... Route handler implementation }); app.get('/users/:id', async (req, res) => { // ... Route handler implementation }); app.put('/users/:id', async (req, res) => { // ... Route handler implementation }); app.delete('/users/:id', async (req, res) => { // ... Route handler implementation }); }
// src/app.ts import { serve } from 'hyperexpress'; export const app = serve();
# 使用官方Node.js的基础镜像 FROM node:lts # 设置工作目录 WORKDIR /usr/src/app # 复制项目文件到工作目录 COPY package*.json ./ # 安装项目依赖 RUN npm install # 复制项目文件到工作目录 COPY . . # 暴露端口3000 EXPOSE 3000 # 启动应用程序 CMD [ "npm", "start" ]
# .dockerignore node_modules npm-debug.log "scripts": { "start": "node src/main.ts" } docker build -t my-hyperexpress-app . docker run -p 3000:3000 my-hyperexpress-app curl http://localhost:3000/users