const { url: URLModel } = require('../../models');
const { getUrlTitle, isValidUrl } = require('../../modules/utils.js');
module.exports = {
get: async (req, res) => {
const urls = await URLModel.findAll();
return res.status(200).json(urls);
},
post: async (req, res) => {
const postUrl = req.body.url;
if (!isValidUrl(postUrl)) {
return res.status(400).send('bad request');
}
getUrlTitle(postUrl, async (err, postTitle) => {
if (err) {
return res.status(404).send('Title not valid');
}
else {
const [postModel, created] = await URLModel.findOrCreate({
where: { url: postUrl },
defaults: { title: postTitle },
})
if (created) {
return res.status(201).json(postModel);
}
return res.status(201).json(postModel);
}
})
},
redirect: (req, res) => {
URLModel
.findOne({
where: {
id: req.params.id
}
})
.then(result => {
if (result) {
return result.update({
visits: result.visits + 1
});
} else {
res.sendStatus(204);
}
})
.then(result => {
res.redirect(result.url);
})
.catch(error => {
console.log(error);
res.sendStatus(500);
});
},
};
- migration, models의 초기값(defaultValue)을 스켈레톤에 추가해줘야 한다
visits: {
type: Sequelize.INTEGER,
defaultValue: 0
},
url.init({
url: DataTypes.STRING,
title: DataTypes.STRING,
visits: {
type: DataTypes.INTEGER,
defaultValue: 0
}
},