시퀄라이즈에서 따로 @types/ 패키지를 설치해주지 않아도 타입스크립트를 지원하기 때문에 그냥 설치는 평소처럼 해주면 된다.
npm install --save sequelize mysql2 sequelize-cli
npm i -D @types/validator @types/node
원래 npx sequelize init 를 해주면 config 와 models migrations 폴더들이 생겼지만
타입스크립트로 지정해줄때는 수동으로 만들어주어야한다.
src
|
----- config / config.ts
----- models / index.ts
----- migrations
export interface EnvConfig {
database: string;
username: string;
password: string | null | undefined;
host: string;
}
export interface Config {
[env: string]: EnvConfig;
}
import dotenv from "dotenv";
dotenv.config();
const config = {
development: {
username: process.env.DB_USERNAME || "root",
password: process.env.DB_PASSWORD,
database: "생성할 스키마 이름",
host: process.env.DB_HOST || "localhost",
dialect: "mysql",
},
test: {
username: "root",
password: null,
database: "database_test",
host: "127.0.0.1",
dialect: "mysql",
},
production: {
username: "root",
password: null,
database: "database_production",
host: "127.0.0.1",
dialect: "mysql",
},
};
export default config;
import { Sequelize } from "sequelize";
import { Config } from "../types/types";
import configData from "../config/config";
const configs: Config = configData;
const env = process.env.NODE_ENV || "development";
const config = configs[env];
interface DB {
[key: string]: any;
sequelize?: Sequelize;
}
const db: DB = {};
const sequelize = new Sequelize(
config.database,
config.username,
config.password === null ? undefined : config.password,
{
host: config.host,
dialect: "mysql",
timezone: "+09:00",
}
);
db.sequelize = sequelize;
export default sequelize;
import sequelzie from "./models";
...
sequelzie
.sync({
force: false,
})
.then(() => {
console.log("데이터 베이스 연결 성공");
})
.catch((err) => {
console.error(err);
});
정상적으로 db에 연결 되었다.
import {
DataTypes,
Model,
Sequelize,
InferAttributes,
InferCreationAttributes,
CreationOptional,
} from "sequelize";
export class Users extends Model<
InferAttributes<Users>,
InferCreationAttributes<Users>
> {
declare id: CreationOptional<number>;
declare email: string;
declare createdAt: CreationOptional<Date>;
declare updatedAt: CreationOptional<Date>;
}
export function initUser(sequelize: Sequelize): void {
Users.init(
{
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
email: {
type: DataTypes.STRING(45),
allowNull: false,
},
createdAt: DataTypes.DATE,
updatedAt: DataTypes.DATE,
},
{
modelName: "Users",
tableName: "users",
timestamps: true,
sequelize,
}
);
}
공식문서 를 보면 어렵지 않게 지정할 수가 있다.
테이블을 모델링한 후 index.ts 에서 테이블을 불러와서 sql내에 테이블을 만들어준다.
import { Sequelize } from "sequelize";
import { Config } from "../types/types";
import configData from "../config/config";
import { initUser } from "./users";
const configs: Config = configData;
const env = process.env.NODE_ENV || "development";
const config = configs[env];
const sequelize = new Sequelize(
config.database,
config.username,
config.password === null ? undefined : config.password,
{
host: config.host,
dialect: "mysql",
timezone: "+09:00",
}
);
// 워크벤치에 테이블 생성
initUser(sequelize);
export default sequelize;
워크벤치에 테이블이 정상적으로 생성되었다.
const formSubmitHandler = async (e: React.MouseEvent<HTMLFormElement>) => {
e.preventDefault();
if (emailref.current) {
const res = await fetch("http://localhost:3002/api/users/signUp", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: emailref.current.value,
}),
});
const data = await res.json();
if (!res.ok) {
throw new Error("에러가 발생했습니다!");
} else {
console.log(data);
emailref.current.value = "";
}
}
};
import { Response, Request, NextFunction } from "express";
import { User } from "../models/users";
import { HttpError } from "../error/http-error";
const signUp = async (req: Request, res: Response, next: NextFunction) => {
const { email } = req.body;
let user;
try {
user = await User.create({
email: email,
});
} catch (err) {
const error = new HttpError("회원가입에 실패 했습니다.", 500);
return next(error);
}
res.json({ message: "정상적으로 회원가입 완료 되었습니다!" });
};
export { signUp as signUp };
DB에 정상적으로 들어왔다.