hyperexpress框架/使用uwebsockets.js核心

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相关的复杂性。

确保你已经定义了taskEverySixSecondstaskEveryThirtyThreeMinutes,和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

npm  install  hyper-express  mikro-orm
npm  install  @mikro-orm/postgresql

module.exports  =  {
    entities:  ['dist/**/*.entity.js'],
    entitiesTs:  ['src/**/*.entity.ts'],
    dbName:  'your_database_name',
    type:  'postgresql',
    host:  'localhost',
    port:  5432,
    user:  'your_database_user',
    password:  'your_database_password',
    debug:  true,
};

import  {  Entity,  PrimaryKey,  Property  }  from  '@mikro-orm/core';

@Entity()
export  class  Example  {
    @PrimaryKey()
    id:  number;

    @Property()
    title:  string;

    @Property()
    content?:  string;

    @Property()
    published:  boolean;
}
import  {  serve  }  from  'hyper-express';
import  {  MikroORM  }  from  '@mikro-orm/core';
import  {  json  }  from  'body-parser';
import  Example  from  './src/Example';  //  Import  your  entity

//  Initialize  MikroORM
const  orm  =  await  MikroORM.init({
    entities:  [Example],
    //  ...  other  MikroORM  options
});

const  app  =  serve();
app.use(json());

//  Create  record
app.post('/examples',  async  (req,  res)  =>  {
    const  example  =  orm.em.create(Example,  req.body);
    await  orm.em.persistAndFlush(example);
    res.json(example);
});

//  Read  records
app.get('/examples',  async  (req,  res)  =>  {
    const  examples  =  await  orm.em.find(Example,  {});
    res.json(examples);
});

//  Read  specific  record
app.get('/examples/:id',  async  (req,  res)  =>  {
    const  example  =  await  orm.em.findOne(Example,  {  id:  parseInt(req.params.id)  });
    if  (!example)  {
      res.status(404).json({  message:  'Not  found'  });
    }  else  {
      res.json(example);
    }
});

//  Update  record
app.put('/examples/:id',  async  (req,  res)  =>  {
    const  example  =  await  orm.em.findOne(Example,  {  id:  parseInt(req.params.id)  });
    if  (!example)  {
      res.status(404).json({  message:  'Not  found'  });
      return;
    }
    orm.em.assign(example,  req.body);
    await  orm.em.flush();
    res.json(example);
});

//  Delete  record
app.delete('/examples/:id',  async  (req,  res)  =>  {
    const  example  =  await  orm.em.findOne(Example,  {  id:  parseInt(req.params.id)  });
    if  (!example)  {
      res.status(404).json({  message:  'Not  found'  });
      return;
    }
    await  orm.em.removeAndFlush(example);
    res.json({  message:  'Deleted  successfully'  });
});

app.listen(3000,  ()  =>  {
    console.log('Server  started  on  http://localhost:3000');
});

const  express  =  require('express');
const  swaggerJsdoc  =  require('swagger-jsdoc');
const  swaggerUi  =  require('swagger-ui-express');

//  ...  其他导入和MikroORM初始化代码

//  Swagger  definition
const  swaggerOptions  =  {
    definition:  {
      openapi:  '3.0.0',
      info:  {
        title:  'Example  API',
        version:  '1.0.0',
        description:  'Example  API  with  Swagger',
      },
    },
    apis:  ['index.js'],  //  Path  to  the  API  docs
};

//  Initialize  Swagger
const  swaggerDocs  =  swaggerJsdoc(swaggerOptions);
const  app  =  express();
app.use(json());

//  Serve  Swagger  UI
app.use('/api-docs',  swaggerUi.serve,  swaggerUi.setup(swaggerDocs));

//  ...  REST  API  routes

//  Swagger  UI  will  be  available  at  http://localhost:3000/api-docs

app.listen(3000,  ()  =>  {
    console.log('Server  started  on  http://localhost:3000');
    console.log('Swagger  UI  available  at  http://localhost:3000/api-docs');
});
/**
  *  @swagger
  *  /examples:
  *     post:
  *       description:  Create  a  new  example
  *       requestBody:
  *         required:  true
  *         content:
  *           application/json:
  *             schema:
  *               type:  object
  *               required:
  *                 -  title
  *               properties:
  *                 title:
  *                   type:  string
  *                 content:
  *                   type:  string
  *                 published:
  *                   type:  boolean
  *       responses:
  *         201:
  *           description:  Example  created  successfully
  */

app.post('/examples',  async  (req,  res)  =>  {
    //  ...  创建记录的代码
});

在  Node.js  项目中,dependencies  文件通常指的是项目的依赖列表,它会列出项目中所有需要用到的外部模块。这个依赖列表会被记录在项目根目录下的  package.json  文件中。

{
    "name":  "my-nodejs-project",
    "version":  "1.0.0",
    "description":  "A  sample  Node.js  project",
    "main":  "app.js",
    "dependencies":  {
      "express":  "^4.17.1"
    }
}

 

 

 

















posted @ 2024-01-19 23:21  pearlcity  阅读(220)  评论(0编辑  收藏  举报