如何在TypeScript中使用API工作

365 阅读4分钟

在TypeScript中使用API

在这篇文章中,我们将看看如何利用TypeScript的力量来创建一个API。微软推出的typeScript是JavaScript的超集。它采用了JavaScript的多功能性,并通过类型定义来改进它。类型定义用于在一个变量上强制执行类型。例如,值5是一个数字。

在TypeScript中,数字就是一个类型定义。TypeScript与很多流行的框架如React.js和React Native一起使用,以构建企业应用程序。

先决条件与预读材料

要跟着本文走,读者需要具备以下条件。

  • 对[HTTP请求]和[API]的基本理解。
  • [Node.js]的基本概念。
  • [TypeScript的基础知识]。

项目设置

为了开始,让我们为我们的项目创建一个工作目录。

# Create a directory 'node-typescript'
mkdir node-typescript

# Choose the new directory as the current directory
cd node-typescript

让我们初始化一个Node.js项目。

# The -y option initializes the project with default settings
npm init -y

Express是一个建立在Node.js上的框架。它被用来构建后端服务器和API。

让我们来安装Express。

# Install express
npm install express

现在,为了在我们的Web API中使用TypeScript,我们需要将TypeScript作为开发者依赖项来安装。

这可以通过以下方式完成。

# The -D option installs typescript as a developer dependency
npm install -D typescript

TypeScript包含静态类型定义,可以在编译时捕捉错误。这是开发人员喜欢TypeScript而不是JavaScript的原因之一。

在开发过程中修复错误比在生产过程中更容易。

现在,让我们为Node.js和Express安装类型定义。

# Type definitions are hosted in the @types npm namespace
npm install -D @types/node @types/express

我们还需要一个tsconfig.json 文件。这个文件是用来向TypeScript编译器解释项目结构的。

让我们来初始化配置。

# Initializes a tsconfig file
npx tsc --init

TypeScript Configuration

图像。TypeScript 配置文件

让我们开始编码吧!

创建一个配置来存储路由

TypeScript是一种面向对象的编程(OOP)语言。一个OOP语言使用对象和类来表示实体。

让我们写一个抽象的类,为我们的路由配置定义骨架。

创建一个名为src 的新文件夹,并在src 内创建一个文件routes.config.ts

mkdir src
cd src

# Create the routes config file
touch routes.config.ts

'routes.config.ts'。

// The express package is imported
import express from "express";

// We define this as an abstract class
// This contains the abstract method: config()
export abstract class RoutesConfig {
  // app is of the TypeScript type: Application, which is defined in @types/express
  app: express.Application;

  // name is the name of the route
  name: string;

  constructor(app: express.Application, name: string) {
    // Initializing the member variables
    this.app = app;
    this.name = name;
    this.config();
  }

  // Name Getter Method
  getName = () => {
    return this.name;
  };

  // config() is defined as an abstract function
  abstract config(): express.Application;
}

你可能想知道为什么上面的类被定义为抽象的。这是因为抽象类不能包含其方法的实现。这个路由配置定义了一个基本的骨架,并可以扩展到创建不同的路由。

定义路由

现在,让我们来定义各种路由。

创建一个新的文件,名为apiRoutes.ts.

touch apiRoutes.ts

'apiRoutes.ts'

// The configuration file that we wrote is imported
import { RoutesConfig } from "./routes.config";
import express from "express";

// Defining data as an array of objects
let data: Object[] = [];

// The ApiRoutes class inherits the RoutesConfig class
export class ApiRoutes extends RoutesConfig {
  constructor(app: express.Application) {
    super(app, "ApiRoutes");
  }

  // The config function contains the routes
  config() {
    // The express.Request and express.Response types are defined in @types/express
    this.app
      .route("/api")
      .get((req: express.Request, res: express.Response) => {
        // The response is sent back
        res.send(`GET Request successful!`);
      });
    // :id defines a query param
    this.app
      .route("/api/:id")
      .get((req: express.Request, res: express.Response) => {
        // The parameter is sent back as a response
        res.send(
          `GET Request successful. Parameter passed is: ${req.params.id}`
        );
      });
    // Post request
    this.app
      .route("/api/post")
      .post((req: express.Request, res: express.Response) => {
        let putData = {
          // The parameter is taken from request.body
          id: req.body.id,
          time: new Date(),
        };
        // the posted data is added to the data array
        data.push(putData);
        res.json(putData);
      });
    return this.app;
  }
}

PUT 和 的请求遵循与 请求相同的格式。而不是 ,我们使用 。DELETE POST this.app.route.post this.app.route.put

编写入口点文件

现在,让我们定义app.ts ,作为进入我们API的入口点。

'app.ts'

import express from "express";
import * as http from "http";
// Importing the base route config file
import { RoutesConfig } from "./routes.config";
// Importing the defined routes
import { ApiRoutes } from "./apiRoutes";

// Initializing the express app
const app: express.Application = express();
// Creating an API server
const server: http.Server = http.createServer(app);
const port = 3000;
// This array holds all the routes
const routes: Array<RoutesConfig> = [];

// Parses the response as JSON
app.use(express.json());

// All the defined routes are pushed into the routes array
routes.push(new ApiRoutes(app));

// Sample get request to check if server is running
app.get("/", (req: express.Request, res: express.Response) => {
  res.status(200).send(`Server is running!`);
});

// The server listens to requests in port 3000
server.listen(port, () => {
  console.log(`Server running locally at port: ${port}`);
});

我们的API现在已经准备好了。

设置TSConfig

为了将TypeScript编译成JavaScript并启用类型检查,我们需要更新我们的tsconfig

'tsconfig.json'

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "inlineSourceMap": true
  }
}

在这里,outDir 关键定义了输出的.js 文件应该存储在一个叫做dist 的目录中。我们还可以创建一个npm脚本,编译.ts 文件,同时启动服务器。

'package.json'。

"scripts": {
    "start": "tsc && node ./dist/app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
},

test 脚本运行tsc 编译命令,同时启动服务器。

测试API

为了测试API,让我们首先运行服务器。

npm run start

Server Run Command

图片。启动API服务器

现在,打开一个单独的终端。我们可以通过使用curl 命令来测试我们的API。cURL是一个命令行工具,用于使用HTTP协议传输数据和测试API。cURL代表客户端URL。

curl --request GET 'localhost:3000/api'

curl --request GET 'localhost:3000/api/10'

# The -H option is used to specify content-type and -d is used to specify the json data
curl --request POST -H "Content-Type: application/json" -d '{"id": "5"}' localhost:3000/api/post

正如你在输出中看到的,我们的基本API工作得很完美。

API Response

帖子的响应情况如下。

POST API Response

摘要

  • 我们设置了一个Node.js项目,并将其配置为与TypeScript一起工作。
  • 我们安装了所需的依赖项和它们相应的类型定义。
  • 抽象类和继承被大量使用,以使API具有可扩展性。这种模式使得编写新的路由更容易。
  • 我们使用cURL测试了API。