使用typeorm数据库
首先在根目录创建db文件夹,在db文件建创建entity文件夹,entity存放各个模块的表模型
在db文件夹创建index.ts,用来导出各个模块的表模型
登录
在db/entity/user.ts
1.Entity指定数据库中的哪个数据表,这里指定 users 数据表
import { Entity, BaseEntity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity({name: 'users'})
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
readonly id!: number;
@Column()
nickname!: string;
@Column()
avatar!: string;
@Column()
job!: string;
@Column()
introduce!: string;
}
2.使用typeorm链接mysql
3.从typeorm引入
import { Connection, getConnection, createConnection } from 'typeorm';
4.引入数据表
import { User, UserAuth, Article, Comment, Tag } from './entity/index';
5.链接mysql数据库
import 'reflect-metadata';
import { Connection, getConnection, createConnection } from 'typeorm';
import { User, UserAuth, Article, Comment, Tag } from './entity/index';
const host = process.env.DATABASE_HOST;
const port = Number(process.env.DATABASE_PORT);
const username = process.env.DATABASE_USERNAME;
const password = process.env.DATABASE_PASSWORD;
const database = process.env.DATABASE_NAME;
let connectionReadyPromise: Promise<Connection> | null = null;
console.log('username', username)
export const prepareConnection = () => {
if (!connectionReadyPromise) {
connectionReadyPromise = (async () => {
try {
const staleConnection = getConnection();
await staleConnection.close();
} catch (error) {
console.log(error);
}
const connection = await createConnection({
type: 'mysql',
host,
port,
username,
password,
database,
entities: [User, UserAuth, Article, Comment, Tag],
synchronize: false,
logging: true,
},6.
return connection;
})();
}
return connectionReadyPromise;
};
6.在接口侧 引入数据库
import { prepareConnection } from 'db/index';
const db = await prepareConnection();
7.引入数据表,使用db获取 指定的数据表,userAuthRepo来操作mysql
import { User, UserAuth } from 'db/entity/index';
const db = await prepareConnection();
const userAuthRepo = db.getRepository(UserAuth);
8.从users表查询数据
const userAuth = await userAuthRepo.findOne(
{
identity_type,
identifier: phone,
},
{
relations: ['user'],
}
);
- 如果userAuth 有数据,则表示登录,没有数据则表示注册
- 如果是登录,从user中获取当前用户的信息,将这些信息一方面存入session,一方面存入cookie,最后返回200状态码,同时将用户信息返回
如果是注册,将这些输入的用户信息,存入users表中,同时将这些信息存入到session和cookie中,同时返回200状态码和这些用户信息
if (userAuth) {
// 已存在的用户
const user = userAuth.user;
const { id, nickname, avatar } = user;
session.userId = id;
session.nickname = nickname;
session.avatar = avatar;
await session.save();
setCookie(cookies, { id, nickname, avatar });
res?.status(200).json({
code: 0,
msg: '登录成功',
data: {
userId: id,
nickname,
avatar,
},
});
} else {
// 新用户,自动注册
const user = new User();
user.nickname = `用户_${Math.floor(Math.random() * 10000)}`;
user.avatar = '/images/avatar.jpg';
user.job = '暂无';
user.introduce = '暂无';
const userAuth = new UserAuth();
userAuth.identifier = phone;
userAuth.identity_type = identity_type;
userAuth.credential = session.verifyCode;
userAuth.user = user;
const resUserAuth = await userAuthRepo.save(userAuth);
const {
user: { id, nickname, avatar },
} = resUserAuth;
session.userId = id;
session.nickname = nickname;
session.avatar = avatar;
await session.save();
setCookie(cookies, { id, nickname, avatar });
res?.status(200).json({
code: 0,
msg: '登录成功',
data: {
userId: id,
nickname,
avatar,
},
});
}