Angular入坑(八):简单讲讲如何自己写一个博客系统

2019-08-18 15:24  |  分类:前端自定义  |  标签: Angular前端框架JavaScript.Angular2解析原理

摘要:上一篇中讲了下Angular的PWA的基础知识。这篇将简单讲讲如何写一个博客系统的思路、细节。

简述

其实一个简单的博客系统实际上很简单,无非就是发文章,显示文章内容。因此在这里,核心功能也是如此,通过系统后台进行文章发布,然年由于前台使用了Angular那么为了保障SEO,使用了Anuglar的SSR功能来进行页面的显示与控制。

博客系统目录结构

  1. ├── app // be source code
  2. ├── controllers
  3. ├── models
  4. ├── routes
  5. ├── api
  6. ├── page
  7. └── web
  8. └── services
  9. ├── bin
  10. ├── config // project config
  11. ├── front-end // fe source code
  12. ├── blog-admin // blog admin manager system
  13. └── blog-index // blog index
  14. ├── logs
  15. ├── middleware // koa middleware
  16. ├── public // fe code build in there.
  17. ├── blog-admin
  18. ├── blog-index // use ng6 ssr.
  19. ├── browser
  20. └── server
  21. ├── error // error page style
  22. └── css
  23. ├── images
  24. └── images-bg
  25. ├── test
  26. ├── uploads
  27. ├── utils
  28. └── views // error page.
  29. └── error

技术栈

  • Koa2
  • Angular
  • MySql

后端实现

使用了Koa2框架实现的,使用了传统的MVC架构,数据库使用MySql。其实整体上来看,后端比较简单,都是对一些表的CRUD操作,最多就是一些复杂的查询。而且表的数量也不多,实际只有7张表。下文会列出这7张表的结构,我们使用JavaScript去描述,这里使用了nodejs的第三方模块sequelize

数据表

  • 文章数据表
  1. const Article = mysql.define('blog_article', {
  2. id: {type: Sequelize.BIGINT, primaryKey: true, autoIncrement: true},
  3. title: {type: Sequelize.STRING(512), allowNull: false},
  4. type: {type: Sequelize.STRING(256), allowNull: false},
  5. tag: {type: Sequelize.STRING(256), allowNull: false},
  6. abstract: {type: Sequelize.TEXT, allowNull: false},
  7. date: {type: Sequelize.BIGINT, allowNull: false},
  8. articleHtml: {type: Sequelize.TEXT('long'), allowNull: false},
  9. articleMd: {type: Sequelize.TEXT('long'), allowNull: false},
  10. coverImg: {type: Sequelize.INTEGER, allowNull: false},
  11. status: {type: Sequelize.STRING(10), allowNull: false},
  12. readCount: {type: Sequelize.INTEGER, allowNull: false, defaultValue: 0},
  13. commentCount: {type: Sequelize.INTEGER, allowNull: false, defaultValue: 0},
  14. seo: {type: Sequelize.STRING(256),allowNull: true}
  15. }, {
  16. tableName: 'blog_article',
  17. timestamps: false,
  18. freezeTableName: true
  19. });
  • 分类标签数据表
  1. const CategoryTag = mysql.define('blog_cat_tag', {
  2. id: {type: Sequelize.BIGINT, primaryKey: true,autoIncrement: true},
  3. type: {type: Sequelize.STRING(100), allowNull:false},
  4. name: {type: Sequelize.STRING(256), allowNull:false},
  5. date: {type: Sequelize.BIGINT, allowNull:false},
  6. count: {type: Sequelize.INTEGER, allowNull:false, defaultValue: 0}
  7. }, {
  8. tableName: 'blog_cat_tag',
  9. timestamps: false,
  10. freezeTableName: true
  11. });
  • 前端错误收集信息表
  1. const mysql = require('./db');
  2. const Sequelize = require('sequelize');
  3. const Cgi = mysql.define('blog_cgi', {
  4. id: {type: Sequelize.BIGINT, primaryKey: true, autoIncrement: true},
  5. content: {type: Sequelize.TEXT, allowNull: false},
  6. type: {type: Sequelize.STRING(256), allowNull: false},
  7. ip: {type: Sequelize.STRING(256), allowNull: false},
  8. date: {type: Sequelize.BIGINT, allowNull: false}
  9. }, {
  10. tableName: 'blog_cgi',
  11. timestamps: false,
  12. freezeTableName: true
  13. });
  14. module.exports = Cgi;
  • 评论信息表
  1. const mysql = require('./db');
  2. const Sequelize = require('sequelize');
  3. const Comment = mysql.define('blog_comment', {
  4. id: {type: Sequelize.BIGINT, primaryKey: true, autoIncrement: true},
  5. article: {type: Sequelize.BIGINT, allowNull: false},
  6. content: {type: Sequelize.TEXT, allowNull: false},
  7. date: {type: Sequelize.BIGINT, allowNull: false},
  8. visitor: {type: Sequelize.STRING(256), allowNull: false},
  9. quotes: {type: Sequelize.TEXT}
  10. }, {
  11. tableName: 'blog_comment',
  12. timestamps: false,
  13. freezeTableName: true
  14. });
  15. module.exports = Comment;
  • 图片信息表
  1. const mysql = require('./db');
  2. const Sequelize = require('sequelize');
  3. const Image = mysql.define('blog_image', {
  4. id: {type: Sequelize.BIGINT, primaryKey: true, autoIncrement: true},
  5. name: {type: Sequelize.STRING, allowNull: false},
  6. ext: {type: Sequelize.STRING, allowNull: false},
  7. mime: {type: Sequelize.STRING, allowNull: false},
  8. path: {type: Sequelize.STRING, allowNull: false},
  9. size: {type: Sequelize.INTEGER, allowNull: false},
  10. date: {type: Sequelize.BIGINT, allowNull: false}
  11. }, {
  12. tableName: 'blog_image',
  13. timestamps: false,
  14. freezeTableName: true
  15. });
  16. module.exports = Image;
  • 用户信息表
  1. const mysql = require('./db');
  2. const Sequelize = require('sequelize');
  3. const User = mysql.define('blog_user', {
  4. id: {type: Sequelize.BIGINT, primaryKey: true, autoIncrement: true},
  5. account: {type: Sequelize.STRING(256), allowNull: false},
  6. name: {type: Sequelize.STRING(256), allowNull: false},
  7. position: {type: Sequelize.STRING(256), allowNull: false},
  8. signature: {type: Sequelize.STRING(256), allowNull: false},
  9. label: {type: Sequelize.STRING(256), allowNull: false},
  10. introduce: {type: Sequelize.TEXT, allowNull: false},
  11. password: {type: Sequelize.TEXT, allowNull: false},
  12. headImg: {type: Sequelize.INTEGER, allowNull: false}
  13. }, {
  14. tableName: 'blog_user',
  15. timestamps: false,
  16. freezeTableName: true
  17. });
  18. module.exports = User;

其实如果要简单的的话,只需要发布文章这一个功能的话,上面有一些表基本都可以不用,仅保留文章信息表就可以,不过这样搭建起来博客系统,只能用于发文章。而没有额外的一些功能。

路由设计

我们后端路由设计也比较简单,使用koa router即可,具体使用方法可以看文档,这里不赘述。这里koa router设计是为了配合后台管理以及前台的AngularRouter实现。

  • /admin/xxx 访问管理端
  • /xxx 访问博客端

至于Angular Router,具体使用见前文Angular入坑(五):路由基础

业务逻辑

后端业务逻辑分为6个模块:

  • 文章管理
  • 标签和类别管理
  • 素材库
  • 评论管理
  • 前端监控
  • 个人信息管理

这里主要是涉及到数据库的操作,包括基础数据的CRUD操作等,这里就不贴代码了,可以参考后文贴出的github仓库地址查看源代码。

这里需要讲解的有几点:

  • 数据库连接,使用了sequelize模块,为了避免硬编码,这里将配置抽出到一个json文件中,在json配置数据相关的配置项。
  1. const Config = require('../../config/database.config');
  2. const Sequelize = require('sequelize');
  3. const mysql = new Sequelize(
  4. Config.dbname,
  5. Config.username,
  6. Config.password, Config.options);
  7. module.exports = mysql;
  • 就像数据库连接配置一样,日志的配置也是如此。
  • 各个数据表模块分离,将对于的数据操放到一个Service类中进行,然后在Controller中调用Service的方法,获取到结果后做进一步处理,如数据封装,修改等。
  • 统一系统的数据结构,这样有利于数据维护,可以新建一个工具类,进行数据转化,传入不同的数据格式的值,传出成统一的数据格式。
  • 异常处理,koa2中由于使用了async-await的形式,因此需要注意好try…catcha…后处理对应的异常。
  • 权限处理方面,则是自定义一个koa2的中间件
  • 其余的包括csrf,session,file upload方面的处理则看你对应的文档即可知悉。

博客端实现

博客端实际上就是个单纯的Anuglar应用。前面一系列文章已经讲了一些博客端的内容了,如SSR,PWA的实现。这里也不赘述了,详细可以看之前的内容。

SEO处理

主要是使用了SSR,而使用了SSR之后还需要对meta标签处理,这里实现的方式是:@angular/platform-browser下的Meta, Title类。基本的流程是,当在服务端获取到数据的时候,通过事件总线,通知所有注册了update-meta事件的模块,进行更新当前页面的meta标签。

  1. this.eventBus.on('update-meta', (data: Event) => {
  2. const meta: MyMeta = data.data;
  3. this.title.setTitle(meta.title);
  4. Object.keys(meta).forEach((val: string) => {
  5. this.meta.updateTag({name: val, content: meta[val]});
  6. this.meta.updateTag({name: `og:${val}`, content: meta[val]});
  7. });
  8. });

这样最终出来的html代码中,就会包含所需的meta,title的内容。

评论功能

这里评论功能实现也比较简单,采用单纯评论-引用评论形式实现。应用评论时使用自定义的,标签将一些关键数据包装一起来,当提交之后对这些数据进行解析提取后进行下一步的后端方面呢的处理。

前端日志上报

这里分错误日志和访问日志;基本原理是在onload事件和onerror事件分别创建一张图片,链接地址为api地址,而后在图片的onload或onnerror事件中把图片移除了。

  1. function error(msg, url, line) {
  2. // 收集上报数据的信息
  3. const REPORT_URL = `${environment.apiURL.cgiError}?type=cli-error&report=`;
  4. // 收集错误信息,发生错误的脚本文件网络地址,用户代理信息,时间
  5. const m: any = {
  6. url,
  7. line,
  8. agent: navigator.userAgent,
  9. time: +new Date
  10. };
  11. if (msg instanceof ErrorEvent) {
  12. m.error = {
  13. msg: msg.message,
  14. lineno: msg.lineno,
  15. filename: msg.filename,
  16. type: msg.type
  17. };
  18. } else {
  19. m.error = msg;
  20. }
  21. // 组装错误上报信息内容URL
  22. url = REPORT_URL + JSON.stringify(m);
  23. let img = new Image;
  24. img.onload = img.onerror = function () {
  25. img = null;
  26. };
  27. // 发送数据到后台cgi
  28. img.src = url;
  29. }
  30. // 监听错误上报
  31. window.onerror = function (msg, url, line) {
  32. error(msg, url, line);
  33. };
  34. window.onload = () => {
  35. setTimeout(() => {
  36. (function _performanc1e() {
  37. const REPORT_URL = `${environment.apiURL.cgiTime}?type=cli-time&report=`;
  38. const perf = window.performance;
  39. const points = ['navigationStart', 'unloadEventStart', 'unloadEventEnd',
  40. 'redirectStart', 'redirectEnd', 'fetchStart', 'domainLookupStart',
  41. 'connectStart', 'requestStart', 'responseStart', 'responseEnd',
  42. 'domLoading', 'domInteractive', 'domContentLoadedEventEnd',
  43. 'domComplete', 'loadEventStart', 'loadEventEnd'];
  44. const timing = perf.timing;
  45. if (perf && timing) {
  46. const arr = [];
  47. const navigationStart = timing[points[0]];
  48. for (let i = 0, l = points.length; i < l; i++) {
  49. arr[i] = timing[points[i]] - navigationStart;
  50. }
  51. const obj: any = {};
  52. points.forEach((val, idx) => {
  53. obj[val] = arr[idx];
  54. });
  55. const url = REPORT_URL + JSON.stringify(obj);
  56. let img = new Image;
  57. img.onload = img.onerror = function () {
  58. img = null;
  59. };
  60. img.src = url;
  61. }
  62. })();
  63. });
  64. };

总结

其实整体来说,博客的功能很简单,也就是文章,分类标签,素材等各种CRUD操作。而后利用Angular实现界面,获取数据,显示数据就完是了。因此这里简单的讲了下我自己博客系统的实现细节。有兴趣的同学,可以看看我博客系统的具体实现。