Explorar el Código

feat:添加新闻列表接口

wangsisi hace 1 día
padre
commit
3afefeeec6
Se han modificado 5 ficheros con 392 adiciones y 0 borrados
  1. 2 0
      app.js
  2. 87 0
      migrations/20250912084440-create-news.js
  3. 84 0
      models/news.js
  4. 128 0
      routes/news.js
  5. 91 0
      seeders/20250912084611-demo-news.js

+ 2 - 0
app.js

@@ -7,6 +7,7 @@ const cors = require('cors')
 
 const indexRouter = require('./routes/index');
 const categoryRouter = require('./routes/category');
+const newsRouter = require('./routes/news');
 
 //文章路由文件
 const adminArticlesRouter = require('./routes/admin/articles');
@@ -34,5 +35,6 @@ app.use('/', indexRouter);
 //文章路由文件
 app.use('/admin/articles', adminArticlesRouter);
 app.use('/category', categoryRouter);
+app.use('/news', newsRouter);
 
 module.exports = app;

+ 87 - 0
migrations/20250912084440-create-news.js

@@ -0,0 +1,87 @@
+'use strict';
+
+/** @type {import('sequelize-cli').Migration} */
+module.exports = {
+  async up (queryInterface, Sequelize) {
+    await queryInterface.createTable('news', {
+      id: {
+        type: Sequelize.INTEGER,
+        primaryKey: true,
+        autoIncrement: true
+      },
+      title: {
+        type: Sequelize.STRING,
+        allowNull: false,
+        comment: '新闻标题'
+      },
+      content: {
+        type: Sequelize.TEXT,
+        allowNull: false,
+        comment: '新闻内容'
+      },
+      summary: {
+        type: Sequelize.TEXT,
+        allowNull: true,
+        comment: '新闻摘要'
+      },
+      author: {
+        type: Sequelize.STRING,
+        allowNull: true,
+        comment: '作者'
+      },
+      source: {
+        type: Sequelize.STRING,
+        allowNull: true,
+        comment: '新闻来源'
+      },
+      coverImage: {
+        type: Sequelize.STRING,
+        allowNull: true,
+        comment: '封面图片URL'
+      },
+      category: {
+        type: Sequelize.STRING,
+        allowNull: true,
+        comment: '新闻分类'
+      },
+      tags: {
+        type: Sequelize.STRING,
+        allowNull: true,
+        comment: '标签,用逗号分隔'
+      },
+      viewCount: {
+        type: Sequelize.INTEGER,
+        defaultValue: 0,
+        comment: '浏览次数'
+      },
+      isPublished: {
+        type: Sequelize.BOOLEAN,
+        defaultValue: true,
+        comment: '是否发布'
+      },
+      publishedAt: {
+        type: Sequelize.DATE,
+        allowNull: true,
+        comment: '发布时间'
+      },
+      createdAt: {
+        type: Sequelize.DATE,
+        allowNull: false
+      },
+      updatedAt: {
+        type: Sequelize.DATE,
+        allowNull: false
+      }
+    });
+
+    // 添加索引
+    await queryInterface.addIndex('news', ['title']);
+    await queryInterface.addIndex('news', ['category']);
+    await queryInterface.addIndex('news', ['isPublished']);
+    await queryInterface.addIndex('news', ['publishedAt']);
+  },
+
+  async down (queryInterface, Sequelize) {
+    await queryInterface.dropTable('news');
+  }
+};

+ 84 - 0
models/news.js

@@ -0,0 +1,84 @@
+// models/News.js
+module.exports = (sequelize, DataTypes) => {
+  const News = sequelize.define('News', {
+    id: {
+      type: DataTypes.INTEGER.UNSIGNED,
+      primaryKey: true,
+      autoIncrement: true
+    },
+    title: {
+      type: DataTypes.STRING,
+      allowNull: false,
+      comment: '新闻标题'
+    },
+    content: {
+      type: DataTypes.TEXT,
+      allowNull: false,
+      comment: '新闻内容'
+    },
+    summary: {
+      type: DataTypes.TEXT,
+      allowNull: true,
+      comment: '新闻摘要'
+    },
+    author: {
+      type: DataTypes.STRING,
+      allowNull: true,
+      comment: '作者'
+    },
+    source: {
+      type: DataTypes.STRING,
+      allowNull: true,
+      comment: '新闻来源'
+    },
+    coverImage: {
+      type: DataTypes.STRING,
+      allowNull: true,
+      comment: '封面图片URL'
+    },
+    category: {
+      type: DataTypes.STRING,
+      allowNull: true,
+      comment: '新闻分类'
+    },
+    tags: {
+      type: DataTypes.STRING,
+      allowNull: true,
+      comment: '标签,用逗号分隔'
+    },
+    viewCount: {
+      type: DataTypes.INTEGER.UNSIGNED,
+      defaultValue: 0,
+      comment: '浏览次数'
+    },
+    isPublished: {
+      type: DataTypes.BOOLEAN,
+      defaultValue: true,
+      comment: '是否发布'
+    },
+    publishedAt: {
+      type: DataTypes.DATE,
+      allowNull: true,
+      comment: '发布时间'
+    }
+  }, {
+    tableName: 'news',
+    timestamps: true,
+    indexes: [
+      {
+        fields: ['title']
+      },
+      {
+        fields: ['category']
+      },
+      {
+        fields: ['isPublished']
+      },
+      {
+        fields: ['publishedAt']
+      }
+    ]
+  });
+
+  return News;
+};

+ 128 - 0
routes/news.js

@@ -0,0 +1,128 @@
+const express = require('express');
+const router = express.Router();
+const { News } = require('../models');
+
+// 获取所有新闻列表
+router.get('/', async (req, res) => {
+  try {
+    const { page = 1, limit = 10, category, isPublished } = req.query;
+    const offset = (page - 1) * limit;
+    
+    const where = {};
+    if (category) {
+      where.category = category;
+    }
+    if (isPublished !== undefined) {
+      where.isPublished = isPublished === 'true';
+    } else {
+      // 默认只显示已发布的新闻
+      where.isPublished = true;
+    }
+    
+    const news = await News.findAndCountAll({
+      where,
+      order: [['publishedAt', 'DESC'], ['createdAt', 'DESC']],
+      limit: parseInt(limit),
+      offset: parseInt(offset)
+    });
+    
+    res.json({
+      data: news.rows,
+      total: news.count,
+      page: parseInt(page),
+      limit: parseInt(limit),
+      totalPages: Math.ceil(news.count / limit)
+    });
+  } catch (error) {
+    res.status(500).json({ error: error.message });
+  }
+});
+
+// 根据ID获取单条新闻
+router.get('/:id', async (req, res) => {
+  try {
+    const news = await News.findByPk(req.params.id);
+    if (!news) {
+      return res.status(404).json({ error: '新闻不存在' });
+    }
+    
+    // 增加浏览次数
+    await news.increment('viewCount');
+    
+    res.json(news);
+  } catch (error) {
+    res.status(500).json({ error: error.message });
+  }
+});
+
+// 添加新新闻
+router.post('/', async (req, res) => {
+  try {
+    const newsData = {
+      ...req.body,
+      publishedAt: req.body.publishedAt || new Date()
+    };
+    const news = await News.create(newsData);
+    res.status(201).json(news);
+  } catch (error) {
+    res.status(500).json({ error: error.message });
+  }
+});
+
+// 更新新闻
+router.put('/:id', async (req, res) => {
+  try {
+    const news = await News.findByPk(req.params.id);
+    if (!news) {
+      return res.status(404).json({ error: '新闻不存在' });
+    }
+    await news.update(req.body);
+    res.json(news);
+  } catch (error) {
+    res.status(500).json({ error: error.message });
+  }
+});
+
+// 删除新闻
+router.delete('/:id', async (req, res) => {
+  try {
+    const news = await News.findByPk(req.params.id);
+    if (!news) {
+      return res.status(404).json({ error: '新闻不存在' });
+    }
+    await news.destroy();
+    res.status(204).send();
+  } catch (error) {
+    res.status(500).json({ error: error.message });
+  }
+});
+
+// 获取新闻分类列表
+router.get('/categories/list', async (req, res) => {
+  try {
+    const categories = await News.findAll({
+      attributes: ['category'],
+      where: {
+        category: {
+          [require('sequelize').Op.ne]: null
+        }
+      },
+      group: ['category'],
+      raw: true
+    });
+    
+    const categoryList = categories
+      .map(item => item.category)
+      .filter(Boolean)
+      .map((category, index) => ({
+        id: index + 1,
+        name: category
+      }));
+    
+    res.json(categoryList);
+  } catch (error) {
+    res.status(500).json({ error: error.message });
+  }
+});
+
+module.exports = router;

+ 91 - 0
seeders/20250912084611-demo-news.js

@@ -0,0 +1,91 @@
+'use strict';
+
+/** @type {import('sequelize-cli').Migration} */
+module.exports = {
+  async up (queryInterface, Sequelize) {
+    await queryInterface.bulkInsert('news', [
+      {
+        title: '飞鸟科技智慧农业解决方案助力乡村振兴',
+        content: '飞鸟科技作为国内领先的智慧农业解决方案提供商,致力于通过先进的技术手段推动农业现代化发展。公司自主研发的智慧农业平台集成了物联网、大数据、人工智能等前沿技术,为农户提供精准种植、智能监测、科学管理等全方位服务。\n\n通过部署智能传感器网络,系统能够实时监测土壤湿度、温度、光照等环境参数,结合气象数据和作物生长模型,为农户提供精准的灌溉、施肥建议。同时,平台还具备病虫害预警功能,能够提前识别潜在风险,帮助农户及时采取防治措施。\n\n截至目前,飞鸟科技的智慧农业解决方案已在全国多个省市成功落地,服务农户超过10万户,累计帮助农户增收超过30%。未来,公司将继续加大研发投入,不断完善产品功能,为乡村振兴战略贡献更大力量。',
+        summary: '飞鸟科技智慧农业解决方案通过物联网、大数据等技术,为农户提供精准种植、智能监测等服务,已服务10万+农户,助力乡村振兴。',
+        author: '飞鸟科技编辑部',
+        source: '飞鸟科技官网',
+        coverImage: 'https://example.com/images/news1.jpg',
+        category: '公司动态',
+        tags: '智慧农业,乡村振兴,物联网,大数据',
+        viewCount: 1250,
+        isPublished: true,
+        publishedAt: new Date('2024-12-01'),
+        createdAt: new Date(),
+        updatedAt: new Date()
+      },
+      {
+        title: '农业物联网技术发展趋势分析',
+        content: '随着5G、物联网、人工智能等技术的快速发展,农业物联网正迎来前所未有的发展机遇。根据最新研究报告显示,全球农业物联网市场规模预计将在2025年达到300亿美元。\n\n在技术层面,传感器技术不断进步,成本持续下降,使得大规模部署成为可能。同时,边缘计算技术的成熟,使得数据处理更加实时高效。人工智能算法的优化,让农业决策更加精准。\n\n在应用场景方面,精准农业、智慧温室、智能养殖等领域需求旺盛。特别是在气候变化和人口增长的双重压力下,提高农业生产效率和质量成为迫切需求。\n\n展望未来,农业物联网将朝着更加智能化、自动化的方向发展,为全球粮食安全提供重要保障。',
+        summary: '农业物联网技术快速发展,市场规模预计2025年达300亿美元,在精准农业、智慧温室等领域应用前景广阔。',
+        author: '技术研究院',
+        source: '农业科技周刊',
+        coverImage: 'https://example.com/images/news2.jpg',
+        category: '技术前沿',
+        tags: '物联网,5G,人工智能,精准农业',
+        viewCount: 890,
+        isPublished: true,
+        publishedAt: new Date('2024-11-28'),
+        createdAt: new Date(),
+        updatedAt: new Date()
+      },
+      {
+        title: '智慧农业助力绿色可持续发展',
+        content: '在"双碳"目标背景下,智慧农业作为绿色农业的重要组成部分,正发挥着越来越重要的作用。通过精准施肥、智能灌溉等技术手段,智慧农业能够显著减少化肥农药使用量,降低环境污染。\n\n研究表明,采用智慧农业技术的农田,化肥使用量可减少20-30%,农药使用量可减少15-25%,同时作物产量还能提升10-15%。这种"减量增效"的模式,既保护了环境,又提高了经济效益。\n\n此外,智慧农业还能通过数据分析和预测,帮助农户制定更加科学的种植计划,避免盲目投入,实现资源的最优配置。\n\n随着环保意识的提升和政策支持力度的加大,智慧农业将在推动农业绿色可持续发展方面发挥更大作用。',
+        summary: '智慧农业通过精准施肥、智能灌溉等技术,实现"减量增效",助力绿色可持续发展,符合"双碳"目标要求。',
+        author: '环保研究院',
+        source: '绿色农业报',
+        coverImage: 'https://example.com/images/news3.jpg',
+        category: '环保科技',
+        tags: '绿色农业,可持续发展,双碳目标,环保',
+        viewCount: 756,
+        isPublished: true,
+        publishedAt: new Date('2024-11-25'),
+        createdAt: new Date(),
+        updatedAt: new Date()
+      },
+      {
+        title: '数字农业平台建设经验分享',
+        content: '数字农业平台作为现代农业发展的重要基础设施,其建设质量直接影响智慧农业的应用效果。在平台建设过程中,需要重点关注以下几个方面:\n\n首先是数据标准化问题。不同厂商的设备和系统往往采用不同的数据格式和协议,需要进行统一的数据标准化处理,确保数据能够互联互通。\n\n其次是系统集成问题。数字农业平台通常需要集成多个子系统,包括环境监测、设备控制、数据分析等,需要做好系统间的接口设计和数据流转。\n\n再次是用户体验问题。平台界面要简洁易用,功能要贴近实际需求,让农户能够快速上手使用。\n\n最后是数据安全问题。农业数据涉及农户隐私和商业机密,需要建立完善的数据安全防护体系。\n\n通过以上几个方面的努力,可以建设出功能完善、安全可靠的数字农业平台。',
+        summary: '数字农业平台建设需要关注数据标准化、系统集成、用户体验和数据安全等关键问题,确保平台功能完善、安全可靠。',
+        author: '平台建设部',
+        source: '数字农业杂志',
+        coverImage: 'https://example.com/images/news4.jpg',
+        category: '技术分享',
+        tags: '数字农业,平台建设,数据标准化,系统集成',
+        viewCount: 634,
+        isPublished: true,
+        publishedAt: new Date('2024-11-22'),
+        createdAt: new Date(),
+        updatedAt: new Date()
+      },
+      {
+        title: '农业大数据应用案例分析',
+        content: '大数据技术在农业领域的应用越来越广泛,通过分析海量的农业数据,可以为农业生产提供科学决策支持。以下是一些典型的应用案例:\n\n案例一:某大型农场通过分析历史气象数据、土壤数据和作物产量数据,建立了产量预测模型,预测准确率达到85%以上,帮助农场提前做好收获和销售计划。\n\n案例二:某蔬菜种植基地利用传感器数据,结合机器学习算法,实现了病虫害的早期识别和预警,病虫害识别准确率达到90%以上,大大减少了农药使用量。\n\n案例三:某水果种植园通过分析市场需求数据和价格走势,优化了种植品种和规模,年收益提升了25%。\n\n这些案例表明,农业大数据具有巨大的应用价值,能够帮助农户提高生产效率、降低成本、增加收益。随着数据采集技术的进步和分析算法的优化,农业大数据的应用前景将更加广阔。',
+        summary: '农业大数据在产量预测、病虫害识别、市场分析等方面应用效果显著,能够帮助农户提高效率、降低成本、增加收益。',
+        author: '数据分析部',
+        source: '农业大数据报告',
+        coverImage: 'https://example.com/images/news5.jpg',
+        category: '案例分析',
+        tags: '大数据,机器学习,产量预测,病虫害识别',
+        viewCount: 1120,
+        isPublished: true,
+        publishedAt: new Date('2024-11-20'),
+        createdAt: new Date(),
+        updatedAt: new Date()
+      }
+    ]);
+
+    console.log('新闻示例数据插入完成!');
+  },
+
+  async down (queryInterface, Sequelize) {
+    await queryInterface.bulkDelete('news', null, {});
+    console.log('新闻示例数据已回滚!');
+  }
+};