npx sequelize-cli model:generate --name url --attributes url:string,title:string,visits:float
└url이라는 이름, string 타입의 url, title, float 타입의 visits를 가지는 모델 생성
npx sequelize-cli db:migrate
└migrate 실행
npx sequelize-cli db:migrate:undo
└migrate 실행취소
└스키마가 바뀌면 새로 migrate해주기 위해 계속 사용해야...
const { url } = require("../../models");
const { getUrlTitle, isValidUrl } = require("../../modules/utils");
module.exports = {
get: async (req, res) => {
try {
const data = await url.findAll();
res.status(200).json(data);
} catch (err) {
res.status(500).send("Server Error Code 500");
}
},
post: async (req, res) => {
const inputUrl = req.body.url;
if (!isValidUrl(inputUrl)) {
return res.status(400).send("Not url address structure");
} else {
getUrlTitle(inputUrl, async (err, title) => {
if (err) return res.status(500).send("Server Error Code 500");
else {
try {
const [data] = await url.findOrCreate({
where: { url: inputUrl, title: title },
});
res.status(201).json(data);
} catch (err) {
res.status(500).send("Server Err Code 500");
}
}
});
}
},
redirect: async (req, res) => {
const inputId = req.params.id;
try {
const data = await url.findOne({ id: inputId });
if (!data) {
return res
.status(404)
.send("Invalid id entered or does not exist data");
} else {
data.update({ visits: data.visits + 1 });
return res.status(301).redirect(data.url);
}
} catch (err) {
return res.status(500).send("Server Error Code 500");
}
},
}
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class url extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
}
url.init({
url: DataTypes.STRING,
title: DataTypes.STRING,
visits: {
type: DataTypes.INTEGER,
defaultValue:0
}
}, {
sequelize,
modelName: 'url',
});
return url;
};
const express = require('express');
const router = express.Router();
const controllerRouter = require('../controllers/links')
/* GET home page. */
router.get('/', controllerRouter.get);
router.post('/', controllerRouter.post);
router.get("/:id", controllerRouter.redirect);
module.exports = router;