|
| 1 | +const ArticleService = require('../services/articleService'); |
| 2 | +const sendJson = require('../utils/sendJson'); |
| 3 | + |
| 4 | +exports.getAllArticles = (req, res) => { |
| 5 | + try { |
| 6 | + const articles = ArticleService.getAll(); |
| 7 | + return sendJson(res, 200, articles); |
| 8 | + } catch (err) { |
| 9 | + console.error(err); |
| 10 | + return sendJson(res, 500, { error: 'Failed to read articles' }); |
| 11 | + } |
| 12 | +}; |
| 13 | + |
| 14 | +exports.getArticleById = (req, res) => { |
| 15 | + try { |
| 16 | + const article = ArticleService.getById(req.params.id); |
| 17 | + |
| 18 | + if (!article) { |
| 19 | + return sendJson(res, 404, { error: 'Article not found' }); |
| 20 | + } |
| 21 | + |
| 22 | + return sendJson(res, 200, article); |
| 23 | + } catch (err) { |
| 24 | + console.error(err); |
| 25 | + return sendJson(res, 500, { error: 'Failed to read article' }); |
| 26 | + } |
| 27 | +}; |
| 28 | + |
| 29 | +exports.createArticle = (req, res) => { |
| 30 | + try { |
| 31 | + let { title, content } = req.body; |
| 32 | + |
| 33 | + |
| 34 | + title = typeof title === 'string' ? title.trim() : ''; |
| 35 | + content = typeof content === 'string' ? content.trim() : ''; |
| 36 | + |
| 37 | + if (!title || !content) { |
| 38 | + return sendJson(res, 400, { error: 'Title and content are required.' }); |
| 39 | + } |
| 40 | + |
| 41 | + |
| 42 | + if (title.length < 3) { |
| 43 | + return sendJson(res, 400, { error: 'Title must be at least 3 characters long.' }); |
| 44 | + } |
| 45 | + |
| 46 | + const article = ArticleService.create({ title, content }); |
| 47 | + return sendJson(res, 201, article); |
| 48 | + } catch (err) { |
| 49 | + console.error(err); |
| 50 | + |
| 51 | + return sendJson(res, 400, { error: err.message || 'Failed to create article.' }); |
| 52 | + } |
| 53 | +}; |
0 commit comments