如何在nodejs中使用typescript编写restful Api。

306 阅读2分钟

本文将介绍如何在 Node.js 中使用 Typescript。我们将使用 Typescript 和 Node.js 库创建一个简单的 restful API 来演示这一点。API 实现基于该站点

1. 安装项目中的依赖

npm init -y

安装项目依赖

在这个应用程序中,我们将使用以下 Node.js 库。

  • TypeScript:具有静态集合类型定义的 TypeScript 编译器。
  • ts-node:允许我们运行和配置 Typescript 执行环境。
  • Express:用于设置和管理基于 Web 的服务器的 Node.js Web 应用程序框架。
  • @types/express:Express 的类型定义。
  • Morgan:Node.js 的 Node.js HTTP 请求记录器中间件。
  • @types/morgan:Morgan 的类型定义。
  • Axios:一个基于 Node.js 承诺的 Node.js HTTP 客户端库,用于发送 HTTP 请求以查询和使用来自 API 的资源。
  • @types/Axios:Axios 的类型定义。
  • Nodemon:用于监视文本编辑器上代码更改的服务器实用程序库。
  • 每当检测到代码更改时,它会自动重新启动服务器。

要安装所有这些库,请运行以下命令。

npm install typescript ts-node express @types/express morgan @types/morgan axios @types/axios nodemon

2. 初始化typescript

要使用 Node.js 执行 Typescript,您需要 tsconfig.json 文件。该文件设置了运行 Typescript 所需的所有环境。您可以手动创建文件或运行 tsc --init 以在项目的根目录中生成示例 tsconfig.json 文件。

tsc --init

配置tsconfig.json

这是一个 Typescript 编译器配置文件,带有指定参数的选项,可简化 Typescript 编译和执行管道。确保您的文件看起来像这样。了解更多tsconfig.json信息。

{
  "compilerOptions": {
    "forceConsistentCasingInFileNames": true,
    "module": "commonjs",
    "esModuleInterop": true,
    "outDir": "./build",
    "rootDir": "./source",
    "target": "es6",
    "skipLibCheck": true,
    "strict": true
  }
}

修改package.json文件

这将设置构建 .ts 文件并将其编译为 .js 文件的命令。在这种情况下,我们可以使用命令 npm run dev 启动开发服务器。

"main": "source/server.ts",
"scripts": {
    "dev": "nodemon source/server.ts",
    "build": "tsc"
}

3. 更新目录结构

您的项目文件和子文件夹应设置如下所示。

在项目目录中创建source文件夹,source文件夹将包含应用程序需要运行的所有 .ts 文件。

|   package-lock.json
|   package.json
|   tsconfig.json
---source
    |   server.ts
    ---controllers
    |       posts.ts
    ---routes
            posts.ts

controllers

创建controllers文件夹,包含posts.ts 文件。该模块将处理所有 API 逻辑,即获取帖子、获取单个帖子、更新帖子、删除帖子和创建帖子。

/** source/controllers/posts.ts */
import { Request, Response, NextFunction } from 'express';
import axios, { AxiosResponse } from 'axios';

interface Post {
  userId: Number;
  id: Number;
  title: String;
  body: String;
}

// getting all posts
const getPosts = async (req: Request, res: Response, next: NextFunction) => {
  // get some posts
  let result: AxiosResponse = await axios.get(`https://jsonplaceholder.typicode.com/posts`);
  let posts: [Post] = result.data;
  return res.status(200).json({
    message: posts
  });
};

// getting a single post
const getPost = async (req: Request, res: Response, next: NextFunction) => {
  // get the post id from the req
  let id: string = req.params.id;
  // get the post
  let result: AxiosResponse = await axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`);
  let post: Post = result.data;
  return res.status(200).json({
    message: post
  });
};

// updating a post
const updatePost = async (req: Request, res: Response, next: NextFunction) => {
  // get the post id from the req.params
  let id: string = req.params.id;
  // get the data from req.body
  let title: string = req.body.title ?? null;
  let body: string = req.body.body ?? null;
  // update the post
  let response: AxiosResponse = await axios.put(`https://jsonplaceholder.typicode.com/posts/${id}`, {
    ...(title && { title }),
    ...(body && { body })
  });
  // return response
  return res.status(200).json({
    message: response.data
  });
};

// deleting a post
const deletePost = async (req: Request, res: Response, next: NextFunction) => {
  // get the post id from req.params
  let id: string = req.params.id;
  // delete the post
  let response: AxiosResponse = await axios.delete(`https://jsonplaceholder.typicode.com/posts/${id}`);
  // return response
  return res.status(200).json({
    message: 'post deleted successfully'
  });
};

// adding a post
const addPost = async (req: Request, res: Response, next: NextFunction) => {
  // get the data from req.body
  let title: string = req.body.title;
  let body: string = req.body.body;
  // add the post
  let response: AxiosResponse = await axios.post(`https://jsonplaceholder.typicode.com/posts`, {
    title,
    body
  });
  // return response
  return res.status(200).json({
    message: response.data
  });
};

export default { getPosts, getPost, updatePost, deletePost, addPost };

我们包括所有必要的 API 方法,例如:

  • getPosts - 获取列表中所有帖子的请求。
  • getPost - 按 id 获取单个帖子的请求。
  • updatePost - 使用新值更新帖子的请求。
  • deletePost - 删除现有帖子的请求。
  • addPost - 向现有列表添加新帖子的请求。

添加routes

创建 routes 文件夹,包含 posts.ts 文件。该文件将路由连接到它们的控制器。定义所有必要的路由来处理相应的 API 端点,例如 GET、POST、PATCH 和 DELETE(在 API 控制器模块中定义)。

/** source/routes/posts.ts */
import express from 'express';
import controller from '../controllers/posts';
const router = express.Router();

router.get('/posts', controller.getPosts);
router.get('/posts/:id', controller.getPost);
router.put('/posts/:id', controller.updatePost);
router.delete('/posts/:id', controller.deletePost);
router.post('/posts', controller.addPost);

export = router;

编写server

server.ts 文件负责设置服务器。这涉及express中间件、路由以及启动服务器。

/** source/server.ts */
import http from 'http';
import express, { Express } from 'express';
import morgan from 'morgan';
import routes from './routes/posts';

const router: Express = express();

/** Logging */
router.use(morgan('dev'));
/** Parse the request */
router.use(express.urlencoded({ extended: false }));
/** Takes care of JSON data */
router.use(express.json());

/** RULES OF OUR API */
router.use((req, res, next) => {
    // set the CORS policy
    res.header('Access-Control-Allow-Origin', '*');
    // set the CORS headers
    res.header('Access-Control-Allow-Headers', 'origin, X-Requested-With,Content-Type,Accept, Authorization');
    // set the CORS method headers
    if (req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods', 'GET PATCH DELETE POST');
        return res.status(200).json({});
    }
    next();
});

/** Routes */
router.use('/', routes);

/** Error handling */
router.use((req, res, next) => {
    const error = new Error('not found');
    return res.status(404).json({
        message: error.message
    });
});

/** Server */
const httpServer = http.createServer(router);
const PORT: any = process.env.PORT ?? 6060;
httpServer.listen(PORT, () => console.log(`The server is running on port ${PORT}`));

运行与测试

npm run dev

这里直接在网站reqbin.com/在线进行的测试,也可以使用postman。

参考文献:www.section.io/engineering…