怎样使用Node.js、TypeScript和Express实现RESTful API服务

打印 上一主题 下一主题

主题 888|帖子 888|积分 2664

Node.js是一个基于 Chrome V8 引擎的 JavaScript 运行情况。Node.js 使用了一个变乱驱动、非阻塞式 I/O 的模型,使其轻量又高效。Express是一个保持最小规模的灵活的 Node.js Web应用步伐开发框架,为Web和移动应用步伐提供一组强大的功能。使用Node.js和Express可以快速的实现一个RESTful API服务。
什么是RESTful API

RESTful API是一种依照 REST(Representational State Transfer,表现层状态转移)架构风格的网络 API 设计,它使用HTTP协议定义的请求方法(GET、POST、PUT、DELETE)来定义对资源的操作。
RESTful API是一种非常流行的API设计风格,它具有以下特点:

  • 使用HTTP协议定义对资源的操作
  • 使用HTTP协议定义的请求方法(GET、POST、PUT、DELETE)来定义对资源的操作
  • 使用JSON作为数据交换格式
  • 使用URL来定义资源
  • 使用HTTP状态码来表现操作结果
怎样使用nodejs和express实现一个RESTful API

在MySQL中创建一个数据库和表
  1. CREATE DATABASE `app`;
  2. CREATE TABLE if not exists user (
  3.     id BIGINT NOT NULL,
  4.     account  varchar(100) DEFAULT '' NOT NULL,
  5.     password varchar(200) DEFAULT '' NOT NULL,
  6.     secret_key varchar(100) DEFAULT '' NOT NULL,
  7.     nick_name varchar(100) DEFAULT '' NOT NULL,
  8.     avatar varchar(300) DEFAULT '' NOT NULL,
  9.     email varchar(100) DEFAULT '' NOT NULL,
  10.     email_verified tinyint(1) DEFAULT 0 NOT NULL,
  11.     phone_number varchar(100) DEFAULT '' NOT NULL,
  12.     phone_numbert_verified tinyint(1) DEFAULT 0 NOT NULL,
  13.     creator_id BIGINT DEFAULT 0 NOT NULL,
  14.     creation_time timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL,
  15.     last_modifier_id BIGINT DEFAULT 0 NOT NULL,
  16.     last_modification_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
  17.     CONSTRAINT pk_user PRIMARY KEY (id),
  18.     CONSTRAINT unique_user_email UNIQUE KEY (email),
  19.     CONSTRAINT unique_user_phone UNIQUE KEY (phone_number)
  20. )
  21. ENGINE=InnoDB
  22. DEFAULT CHARSET=utf8mb4
  23. COLLATE=utf8mb4_unicode_ci
复制代码
从GitHub下载项目模板一个基于nodejs、TypeScript和express的web模板

创建User实体类
  1. class User {
  2.     public id!: bigint;
  3.     public account: string;
  4.     public password: string;
  5.     public secret_key: string
  6.     public nick_name: string;
  7.     public avatar: string;
  8.     public email: string;
  9.     public phone_number: string;
  10.     public creator_id: bigint;
  11.     public creation_time!: Date;
  12.     public last_modifier_id!: bigint;
  13.     public last_modification_time!: Date;
  14.     constructor(account: string, password: string, secret_key: string, nick_name: string, avatar: string, email: string,
  15.         phone_number: string, creator_id: bigint) {
  16.         this.account = account;
  17.         this.password = password;
  18.         this.secret_key = secret_key;
  19.         this.nick_name = nick_name;
  20.         this.avatar = avatar;
  21.         this.email = email;
  22.         this.phone_number = phone_number;
  23.         this.creator_id = creator_id;
  24.     }
  25. }
  26. export default User;
复制代码
创建UserService类
  1. import User from "../models/User";
  2. import { connection } from '../utils/db';
  3. import PasswordSecurity from '../utils/password-security';
  4. import { SnowflakeId } from "../utils/snowflakeid";
  5. class UserService {
  6.     public async create(user: User): Promise<User> {
  7.         return new Promise<User>((resolve, reject) => {
  8.             try {
  9.                 const passwordSecurity = new PasswordSecurity();
  10.                 const secret_key = passwordSecurity.createSalt();
  11.                 user.id = SnowflakeId.newId();
  12.                 user.secret_key = secret_key;
  13.                 user.password = passwordSecurity.createHash(user.password, secret_key);
  14.                 user.creation_time = new Date();
  15.                 user.last_modifier_id = user.creator_id;
  16.                 user.last_modification_time = new Date();
  17.                 connection.query('insert into user (id, account, password, secret_key, nick_name, avatar, email, phone_number, creator_id, creation_time, last_modifier_id, last_modification_time)'
  18.                     + 'values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
  19.                     [user.id, user.account, user.password, user.secret_key, user.nick_name, user.avatar, user.email, user.phone_number, user.creator_id, user.creation_time, user.last_modifier_id, user.last_modification_time],
  20.                     function (error: any, result: any) {
  21.                         if (error) {
  22.                             console.log('Error: ' + error.message);
  23.                             reject(error);
  24.                         } else {
  25.                             resolve(user);
  26.                         }
  27.                     });
  28.             } catch (e) {
  29.                 reject(e)
  30.             }
  31.         })
  32.     }
  33.     public async getByAccount(account: string): Promise<User> {
  34.         return new Promise<User>((resolve, reject) => {
  35.             try {
  36.                 connection.query('select * from user where account = ?', [account], function (error: any, result: any) {
  37.                     if (error) {
  38.                         console.log('Error: ' + error.message);
  39.                         reject(error);
  40.                     } else {
  41.                         resolve(result[0]);
  42.                     }
  43.                 });
  44.             } catch (e) {
  45.                 reject(e)
  46.             }
  47.         })
  48.     }
  49.     public async getById(id: number): Promise<User> {
  50.         return new Promise<User>((resolve, reject) => {
  51.             try {
  52.                 connection.query('select * from user where id = ?', [id], function (error: any, result: any) {
  53.                     if (error) {
  54.                         console.log('Error: ' + error.message);
  55.                         reject(error);
  56.                     } else {
  57.                         resolve(result[0]);
  58.                     }
  59.                 })
  60.             } catch (e) {
  61.                 reject(e)
  62.             }
  63.         });
  64.     }
  65.     public async getByEmail(email: string): Promise<User> {
  66.         return new Promise<User>((resolve, reject) => {
  67.             try {
  68.                 connection.query('select * from user where email = ?', [email], function (error: any, result: any) {
  69.                     if (error) {
  70.                         console.log('Error: ' + error.message);
  71.                         reject(error);
  72.                     } else {
  73.                         resolve(result[0]);
  74.                     }
  75.                 })
  76.             } catch (e) {
  77.                 reject(e)
  78.             }
  79.         })
  80.     }
  81.     public async getByPhoneNumber(phone_number: string): Promise<User> {
  82.         return new Promise<User>((resolve, reject) => {
  83.             try {
  84.                 connection.query('select * from user where phone_number = ?', [phone_number], function (error: any, result: any) {
  85.                     if (error) {
  86.                         console.log('Error: ' + error.message);
  87.                         reject(error);
  88.                     } else {
  89.                         resolve(result[0]);
  90.                     }
  91.                 })
  92.             } catch (e) {
  93.                 reject(e)
  94.             }
  95.         })
  96.     }
  97.     public async update(user: User): Promise<User> {
  98.         return new Promise((resolve, reject) => {
  99.             try {
  100.                 connection.query('update user set account = ?, password = ?, secret_key = ?, name = ?, avatar = ?, email = ?, phone_number = ?, creator_id = ?, creation_time = ?, last_modifier_id = ?, last_modification_time = ? where id = ?',
  101.                     [user.account, user.password, user.secret_key, user.nick_name, user.avatar, user.email, user.phone_number, user.last_modifier_id, user.last_modification_time, user.id], function (error, result) {
  102.                         if (error) {
  103.                             console.log('Error: ' + error.message);
  104.                             reject(error)
  105.                         } else {
  106.                             resolve(user);
  107.                         }
  108.                     });
  109.             } catch (e) {
  110.                 reject(e);
  111.             }
  112.         });
  113.     }
  114.     public async delete(id: number): Promise<void> {
  115.         return new Promise<void>((resolve, reject) => {
  116.             try {
  117.                 connection.query('delete from user where id = ?', [id], function (error, result) {
  118.                     if (error) {
  119.                         console.log('Error: ' + error.message);
  120.                         reject(error)
  121.                     } else {
  122.                         resolve();
  123.                     }
  124.                 });
  125.             } catch (e) {
  126.                 reject(e);
  127.             }
  128.         })
  129.     }
  130. }
  131. export default new UserService();
复制代码
创建UserController
  1. import { Request, Response } from 'express';
  2. import User  from '../models/User';
  3. import UserService from '../services/UserService';
  4. import { success, error } from '../utils/json-result'
  5. import { Get, Post, Put, Delete, Controller} from '../utils/routing-controllers'
  6. @Controller('/api/user')
  7. class UserController {
  8.     constructor() { }
  9.     @Post('/')
  10.     public async create(req: Request, res: Response): Promise<any> {
  11.         try {
  12.             var user = new User(
  13.                 req.body.name,
  14.                 req.body.password,
  15.                 req.body.secret_key,
  16.                 req.body.nick_name,
  17.                 req.body.avatar == null || req.body.avatar == undefined ? '' : req.body.avatar,
  18.                 req.body.email,
  19.                 req.body.phone_number,
  20.                 req.body.creator_id == null || req.body.creator_id == undefined ? 0 : req.body.creator_id);
  21.    
  22.             if (user.account == null || user.account == '') {
  23.                 error(res, "用户名不能为空");
  24.                 return;
  25.             }
  26.             if (user.password == null || user.password == '') {
  27.                 error(res, "密码不能为空");
  28.                 return;
  29.             }
  30.             if (user.email == null || user.email == '') {
  31.                 error(res, "邮箱不能为空");
  32.                 return;
  33.             }
  34.             if (user.phone_number == null || user.phone_number == '') {
  35.                 error(res, "手机号不能为空");
  36.                 return;
  37.             }
  38.             var existingUser = await UserService.getByAccount(user.account);
  39.             if (existingUser != null) {
  40.                 error(res, "用户已存在");
  41.                 return
  42.             }
  43.             existingUser = await UserService.getByEmail(user.email);
  44.             if (existingUser != null) {
  45.                 error(res, "邮箱已存在");
  46.                 return;
  47.             }
  48.             existingUser = await UserService.getByPhoneNumber(user.phone_number);
  49.             if (existingUser != null) {
  50.                 error(res, "手机号已存在");
  51.                 return;
  52.             }
  53.             UserService.create(user).then(result => {
  54.                 success(res, result);
  55.             });
  56.         } catch (err: any) {
  57.             console.error(err);
  58.             error(res, err.message);
  59.         }
  60.     }
  61.     @Get('/')
  62.     public get(req: Request, res: Response): any {
  63.         res.send('users');
  64.     }
  65.     @Put('/')
  66.     public update(req: Request, res: Response): any {
  67.         res.send('update user');
  68.         // 处理更新用户的请求
  69.     }
  70.     @Delete('/')
  71.     public delete(req: Request, res: Response): void {
  72.         res.send('delete user');
  73.         // 处理删除用户的请求
  74.     }
  75. }
  76. export default UserController;
复制代码
启动服务
  1. npm start
复制代码
测试
  1. curl -X POST -H "Content-Type: application/json" -d '{"account":"admin","password":"123456","secret_key":"123456","nick_name":"admin","email":"22222@qq.com","phone_number":"13888888888"}' http://localhost:3000/api/user
复制代码
返回结果
  1. {"account":"admin","password":"43ad945a38257858c962d7e703bf090db019e61efda2edd34a48480e8da51b4a12c1f1d04ed06feced130bfa30e76e41f08762ee7e04fe038b2ecd4b90d43c94","secret_key":"b4689647434328c65a18cb7707b74734","nick_name":"admin","avatar":"","email":"22222@qq.com","phone_number":"13888888888","creator_id":0,"id":"11087864288776192","creation_time":"2024-06-02T14:19:12.888Z","last_modifier_id":0,"last_modification_time":"2024-06-02T14:19:12.888Z"}
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

莱莱

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表