使用typeorm数据库

首先在根目录创建db文件夹,在db文件建创建entity文件夹,entity存放各个模块的表模型
在db文件夹创建index.ts,用来导出各个模块的表模型

登录

在db/entity/user.ts
1.Entity指定数据库中的哪个数据表,这里指定 users 数据表

  1. import { Entity, BaseEntity, PrimaryGeneratedColumn, Column } from 'typeorm';
  2. @Entity({name: 'users'})
  3. export class User extends BaseEntity {
  4. @PrimaryGeneratedColumn()
  5. readonly id!: number;
  6. @Column()
  7. nickname!: string;
  8. @Column()
  9. avatar!: string;
  10. @Column()
  11. job!: string;
  12. @Column()
  13. introduce!: string;
  14. }

2.使用typeorm链接mysql
3.从typeorm引入

  1. import { Connection, getConnection, createConnection } from 'typeorm';

4.引入数据表

  1. import { User, UserAuth, Article, Comment, Tag } from './entity/index';

5.链接mysql数据库

  1. import 'reflect-metadata';
  2. import { Connection, getConnection, createConnection } from 'typeorm';
  3. import { User, UserAuth, Article, Comment, Tag } from './entity/index';
  4. const host = process.env.DATABASE_HOST;
  5. const port = Number(process.env.DATABASE_PORT);
  6. const username = process.env.DATABASE_USERNAME;
  7. const password = process.env.DATABASE_PASSWORD;
  8. const database = process.env.DATABASE_NAME;
  9. let connectionReadyPromise: Promise<Connection> | null = null;
  10. console.log('username', username)
  11. export const prepareConnection = () => {
  12. if (!connectionReadyPromise) {
  13. connectionReadyPromise = (async () => {
  14. try {
  15. const staleConnection = getConnection();
  16. await staleConnection.close();
  17. } catch (error) {
  18. console.log(error);
  19. }
  20. const connection = await createConnection({
  21. type: 'mysql',
  22. host,
  23. port,
  24. username,
  25. password,
  26. database,
  27. entities: [User, UserAuth, Article, Comment, Tag],
  28. synchronize: false,
  29. logging: true,
  30. },6.
  31. return connection;
  32. })();
  33. }
  34. return connectionReadyPromise;
  35. };

6.在接口侧 引入数据库

  1. import { prepareConnection } from 'db/index';
  2. const db = await prepareConnection();

7.引入数据表,使用db获取 指定的数据表,userAuthRepo来操作mysql

  1. import { User, UserAuth } from 'db/entity/index';
  2. const db = await prepareConnection();
  3. const userAuthRepo = db.getRepository(UserAuth);

8.从users表查询数据

  1. const userAuth = await userAuthRepo.findOne(
  2. {
  3. identity_type,
  4. identifier: phone,
  5. },
  6. {
  7. relations: ['user'],
  8. }
  9. );
  1. 如果userAuth 有数据,则表示登录,没有数据则表示注册
  2. 如果是登录,从user中获取当前用户的信息,将这些信息一方面存入session,一方面存入cookie,最后返回200状态码,同时将用户信息返回
  3. 如果是注册,将这些输入的用户信息,存入users表中,同时将这些信息存入到session和cookie中,同时返回200状态码和这些用户信息

    1. if (userAuth) {
    2. // 已存在的用户
    3. const user = userAuth.user;
    4. const { id, nickname, avatar } = user;
    5. session.userId = id;
    6. session.nickname = nickname;
    7. session.avatar = avatar;
    8. await session.save();
    9. setCookie(cookies, { id, nickname, avatar });
    10. res?.status(200).json({
    11. code: 0,
    12. msg: '登录成功',
    13. data: {
    14. userId: id,
    15. nickname,
    16. avatar,
    17. },
    18. });
    19. } else {
    20. // 新用户,自动注册
    21. const user = new User();
    22. user.nickname = `用户_${Math.floor(Math.random() * 10000)}`;
    23. user.avatar = '/images/avatar.jpg';
    24. user.job = '暂无';
    25. user.introduce = '暂无';
    26. const userAuth = new UserAuth();
    27. userAuth.identifier = phone;
    28. userAuth.identity_type = identity_type;
    29. userAuth.credential = session.verifyCode;
    30. userAuth.user = user;
    31. const resUserAuth = await userAuthRepo.save(userAuth);
    32. const {
    33. user: { id, nickname, avatar },
    34. } = resUserAuth;
    35. session.userId = id;
    36. session.nickname = nickname;
    37. session.avatar = avatar;
    38. await session.save();
    39. setCookie(cookies, { id, nickname, avatar });
    40. res?.status(200).json({
    41. code: 0,
    42. msg: '登录成功',
    43. data: {
    44. userId: id,
    45. nickname,
    46. avatar,
    47. },
    48. });
    49. }