基于nodeJS从0到1实现一个CMS全栈项目(中)(含源码)

今天给你们介绍的主要是咱们全栈CMS系统的后台部分,因为后台部分涉及的点比较多,我会拆解成几部分来说解,若是对项目背景和技术栈不太了解,能够查看个人上一篇文章javascript

基于nodeJS从0到1实现一个CMS全栈项目(上)css

这篇文章除了会涉及node的知识,还会涉及到redis(一个高性能的key-value数据库),前端领域的javascript大部分高级技巧以及ES6语法,因此在学习以前但愿你们对其有所了解。前端

摘要

本文主要介绍CMS服务端部分的实现,具体包括以下内容:vue

  • 如何使用babel7让node支持更多es6+语法以及nodemon实现项目文件热更新和自动重启
  • node项目的目录结构设计和思想
  • 如何基于ioredis和json-schema本身实现一个类schema的基础库
  • 基于koa-session封装一个sessionStore库
  • 基于koa/multer封装文件处理的工具类
  • 实现自定义的koa中间件和restful API
  • 模版引擎pug的基本使用及技巧

因为每个技术点实现的细节不少,建议先学习相关内容,若是不懂的能够和我交流。java

正文

1.如何使用babel7让node支持更多es6+语法以及nodemon实现项目文件热更新和自动重启

最新的node虽然已经支持大部分es6+语法,可是对于import,export这些模块化导入导出的API尚未完全支持,因此咱们能够经过babel去编译支持,若是你习惯使用commonjs的方式,也能够直接使用。这里我直接写出个人配置:node

  1. package.json安装babel模块和nodemon热重启
"devDependencies": {
    "@babel/cli": "^7.5.5",
    "@babel/core": "^7.5.5",
    "@babel/node": "^7.5.5",
    "@babel/plugin-proposal-class-properties": "^7.5.5",
    "@babel/plugin-proposal-decorators": "^7.4.4",
    "@babel/preset-env": "^7.5.5",
    "nodemon": "^1.19.1"
  },
复制代码
  1. 配置.babelrc文件,让node支持import,export,class以及装饰器:
// .babelrc
{
    "presets": [
      [
        "@babel/preset-env",
        {
          "targets": {
            "node": "current"
          }
        }
      ]
    ],
    "plugins": [
      ["@babel/plugin-proposal-decorators", { "legacy": true }],
      ["@babel/plugin-proposal-class-properties", { "loose" : true }]
    ]
  }
复制代码
  1. 配置启动脚本。为了使用npm的方式启动项目,咱们在package.json里配置以下脚本:
"scripts": {
    "start": "export NODE_ENV=development && nodemon -w src --exec \"babel-node src\"",
    "build": "babel src --out-dir dist",
    "run-build": "node dist",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
复制代码

有关babel7和nodemon以及npm的一些配置问题和使用方式,不过有不懂的能够在文章末尾和我交流。这里提供几个学习连接:react

至此,咱们node项目的基础设施基本搭建完成了,接下来咱们继续深刻服务端设计底层。jquery

2.node项目的目录结构设计和思想

首先来看看咱们完成后的目录设计:webpack

项目参考了不少经典资料和MDN的文档,采用经典的MVC模式,为了方便理解,笔者特地作了一个大体的导图:

这种模式用于应用程序的分层开发,方便后期的管理和扩展,并提供了清晰的设计架构。

  • Model层咱们管理数据对象,它也能够带有逻辑,在数据变化时更新控制器。
  • View层主要用来展现数据的视图。
  • Controller控制器做用于模型和视图上。它控制数据流向模型对象,并在数据变化时更新视图,使视图与模型分离开。

3.基于ioredis和json-schema本身实现一个类schema的基础库

在项目开发前,咱们须要根据业务结构和内容设计数据模型,数据库部分我这里采用的是redis+json-schema,原本想使用mongodb来实现主数据的存储,可是考虑到本身对新方案的研究和想本身经过二次封装redis实现类mongoose的客户端管理框架,因此这里会采用此方案,关于mongoDB的实现,我以前也有项目案例,感兴趣能够一块儿交流优化。css3

咱们来先看看CMS设计的视图和内容,咱们分管理端和客户端,管理端主要的模块有:

  1. 登陆模块

2. 首页配置管理模块

配置页主要包括header头部,banner位,bannerSider侧边栏和文章赞扬设置,咱们对对它作一个单独的config数据库。 3. 文章管理模块

这里咱们须要对文章数据进行存储,包括文章分类,文章首图,文章内容等信息,以下:
4. 图片管理

图片管理主要是方便博主管理图片信息,定位图片的来源,方便后期作埋点跟踪。

  1. 网站统计

网站统计只是一个雏形,博主能够根据本身需求作统计分析,提升更大的自定义。

  1. 管理员模块

这里用来管理系统的管理员,能够分配管理员权限等。关于权限的设计,能够有更复杂的模式,后面有须要也能够相互交流。

根据以上的展现,咱们大体知道了咱们须要设计哪些数据库模型,接下来我先带你们封装redis-schema,也是咱们用到的数据库的底层工具:

// lib/schema.js
import { validate } from 'jsonschema'
import Redis from 'ioredis'

const redis = new Redis()

class RedisSchema {
    constructor(schemaName, schema) {
        this.schemaName = schemaName
        this.schema = schema
        this.redis = redis
    }

    validate(value, schema, cb) {
        const { valid, errors } = validate(value, schema);
        if(valid) {
            return cb()
        }else {
            return errors.map(item => item.stack)
        }
    }

    get() {
        return this.redis.get(this.schemaName)
    }

    // 获取整个hash对象
    hgetall() {
        return this.redis.hgetall(this.schemaName)
    }

    // 获取指定hash对象的属性值
    hget(key) {
        return this.redis.hget(this.schemaName, key)
    }

    // 经过索引获取列表中的元素
    lindex(index) {
        return this.redis.lindex(this.schemaName, index)
    }

    // 获取列表中指定范围的元素
    lrange(start, end) {
        return this.redis.lrange(this.schemaName, start, end)
    }

    // 获取列表的长度
    llen() {
        return this.redis.llen(this.schemaName)
    }

    // 检测某个schemaName是否存在
    exists() {
        return this.redis.exists(this.schemaName)
    }

    // 给某个schemaName设置过时时间,单位为秒
    expire(time) {
        return this.redis.expire(this.schemaName, time)
    }

    // 移除某个schemaName的过时时间
    persist() {
        return this.redis.persist(this.schemaName)
    }

    // 修改schemaName名
    rename(new_schemaName) {
        return this.redis.rename(this.schemaName, new_schemaName)
    }


    set(value, time) {
        return this.validate(value, this.schema, () => {
            if(time) {
                return this.redis.set(this.schemaName, value, "EX", time)
            }else {
                return this.redis.set(this.schemaName, value)
            }
        })
    }

    // 将某个schema的值自增指定数量的值
    incrby(num) {
        return this.redis.incrby(this.schemaName, num)
    }

    // 将某个schema的值自增指定数量的值
    decrby(num) {
        return this.redis.decrby(this.schemaName, num)
    }

    hmset(key, value) {
        if(key) {
            if(this.schema.properties){
                return this.validate(value, this.schema.properties[key], () => {
                    return this.redis.hmset(this.schemaName, key, JSON.stringify(value))
                })
            }else {
                return this.validate(value, this.schema.patternProperties["^[a-z0-9]+$"], () => {
                    return this.redis.hmset(this.schemaName, key, JSON.stringify(value))
                })
            }
            
        }else {
            return this.validate(value, this.schema, () => {
                // 将第一层键值json化,以便redis能正确存储键值为引用类型的值
                for(key in value) {
                    let v = value[key];
                    value[key] = JSON.stringify(v);
                }
                return this.redis.hmset(this.schemaName, value)
            })
        }
    }

    hincrby(key, num) {
        return this.redis.hincrby(this.schemaName, key, num)
    }

    lpush(value) {
        return this.validate(value, this.schema, () => {
            return this.redis.lpush(this.schemaName, JSON.stringify(value))
        })
    }

    lset(index, value) {
        return this.redis.lset(this.schemaName, index, JSON.stringify(value))
    }

    lrem(count, value) {
        return this.redis.lrem(this.schemaName, count, value)
    }

    del() {
        return this.redis.del(this.schemaName)
    }

    hdel(key) {
        return this.redis.hdel(this.schemaName, key)
    }
}

export default RedisSchema
复制代码

这个笔者本身封装的库还有跟多可扩展的地方,好比增长类事物处理,保存前拦截器等等,我会在第二版改进,这里只供参考。关于json-schema更多的知识,若有不懂,能够在咱们的交流区沟通学习。 咱们定义一个管理员的schema:

/db/schema/admin.js
import RedisSchema from '../../lib/schema'

// 存放管理员数据
const adminSchema = new RedisSchema('admin', {
    id: "/admin",
    type: "object",
    properties: {
        username: {type: "string"},
        pwd: {type: "string"},
        role: {type: "number"}   // 0 超级管理员 1 普通管理员
      }
  })

export default adminSchema
复制代码

由上能够知道,管理员实体包含username用户名,密码pwd,角色role,对于其余的数据库设计,也能够参考此方式。

4.基于koa-session封装一个sessionStore库

因为session的知识网上不少资料,这里就不耽误时间了,这里列出个人方案:

function getSession(sid) {
    return `session:${sid}`
}

class sessionStore {
    constructor (client) {
        this.client = client
    }

    async get (sid) {
        let id = getSession(sid)
        let result = await this.client.get(id)
        if (!result) {
            return null
        } else {
            try{
                return JSON.parse(result)
            }catch (err) {
                console.error(err)
            }
        }
    }

    async set (sid, value, ttl) {
        let id = getSession(sid)

        try {
            let sessStr = JSON.stringify(value)
            if(ttl && typeof ttl === 'number') {
                await this.client.set(id, sessStr, "EX", ttl)
            } else {
                await this.client.set(id, sessStr)
            }
        } catch (err) {
            console.log('session-store', err)
        }
    }

    async destroy (sid) {
        let id = getSession(sid)
        await this.client.del(id)
    }
}

module.exports = sessionStore
复制代码

这里主要实现了session的get,set,del操做,咱们主要用来处理用户的登陆信息。

5.基于koa/multer封装文件处理的工具类

文件上传的方案我是在github上看的koa/multer,基于它封装文件上传的库,但凡涉及到文件上传的操做都会使用它。

import multer from '@koa/multer'
import { resolve } from 'path'
import fs from 'fs'

const rootImages = resolve(__dirname, '../../public/uploads')
//上传文件存放路径、及文件命名
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, rootImages)
    },
    filename: function (req, file, cb) {
        let [name, type] = file.originalname.split('.');
        cb(null, `${name}_${Date.now().toString(16)}.${type}`)
    }
})
//文件上传限制
const limits = {
    fields: 10,//非文件字段的数量
    fileSize: 1024 * 1024 * 2,//文件大小 单位 b
    files: 1//文件数量
}

export const upload = multer({storage,limits})

// 删除文件
export const delFile = (path) => {
    return new Promise((resolve, reject) => {
        fs.unlink(path, (err) => {
            if(err) {
                reject(err)
            }else {
                resolve(null)
            }
        })
    }) 
}

// 删除文件夹
export function deleteFolder(path) {
    var files = [];
    if(fs.existsSync(path)) {
        files = fs.readdirSync(path);
        files.forEach(function(file,index){
            var curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()) { // recurse
                deleteFolder(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
}

export function writeFile(path, data, encode) {
    return new Promise((resolve, reject) => {
        fs.writeFile(path, data, encode, (err) => {
            if(err) {
                reject(err)
            }else {
                resolve(null)
            }
        })
    })
}
复制代码

这套方案包含了上传文件,删除文件,删除目录的工具方法,能够拿来当轮子使用到其余项目,也能够基于个人轮子作二次扩展。

关于实现自定义的koa中间件和restful API和模版引擎pug的基本使用及技巧部分,因为时间缘由,我会在明天继续更新,以上部分若有不懂的,能够和笔者交流学习。

最后

接下来的两天将推出服务端剩下的部分,CMS全栈的管理后台和客户端部分的实现。包括:

  • 实现自定义的koa中间件和restful API
  • koa路由和service层实现
  • 模版引擎pug的基本使用及技巧
  • vue管理后台页面的实现及源码分享
  • react客户端前台的具体实现及源码分享
  • pm2部署以及nginx服务器配置

项目完整源码地址我会在十一以前告诉你们,欢迎在公众号《趣谈前端》加入咱们一块儿讨论。

更多推荐

相关文章
相关标签/搜索