nodessr搭建项目(依赖注入版)

2019-06-15  本文已影响0人  zxhnext

一、这里我们使用awilix来实现依赖注入

来看一下app.js文件

import Koa from "koa";
import serve from 'koa-static';
import config from "./config";
import render from 'koa-swig';
import co from 'co';
import log4js from 'log4js';
import errorHandler from "./middleawares/errorHandler";
import { 
    Lifetime, 
    createContainer 
} from 'awilix';
import { 
    scopePerRequest, 
    loadControllers 
} from 'awilix-koa';
const app = new Koa();
// 创建一个容器,管理所有的服务和路由
const container = createContainer();
// 把所有的service注册容器
// 每一个controller把需要的service注册进去
container.loadModules([__dirname + "/services/*.js"], {
    // BookService -> bookservice
    formatName: "camelCase",
    registerOptions: {
        lifetime: Lifetime.SCOPED
    }
})
app.use(scopePerRequest(container));

//前端模板
//co的作用是把 *函数全部自动向下执行 next -> next -> done
//async await 语法糖版本 koa-swig 并为KOA2 升级 KOA1 
app.context.render = co.wrap(render({
    root: config.viewDir,
    autoescape: true,
    // cache: 'memory', // disable, set to false 模版缓存,开发时设为false,上线时再这样设置
    cache: false,
    varControls: ["[[", "]]"],
    ext: 'html',
    writeBody: false
}));
log4js.configure({
    appenders: {
        cheese: {
            type: 'file',
            filename: './logs/yd-log.log'
        }
    },
    categories: {
        default: {
            appenders: ['cheese'],
            level: 'error'
        }
    }
});
const logger = log4js.getLogger('cheese');
errorHandler.error(app, logger);
app.use(loadControllers(__dirname + "/controllers/*.js"), {
    cwd: __dirname
});
//配置静态资源
app.use(serve(config.staticDir));
app.listen(config.port, () => {
    console.log("服务已启动🍺");
});

路由中使用

import { 
    route,
    GET
} from 'awilix-koa';
const cheerio = require('cheerio')
@route("/books")
class BooksController {
    constructor({bookService}) {
        this.bookService = bookService;
    }
    @route("/index")
    @GET()
    async actionIndex(ctx, next) {
        const result = await this.bookService.getData();
        // console.log("整个node系统是否通了", result);
        const html = await ctx.render("books/pages/index", {
            data: result.data
        });
        if (ctx.request.header["x-pjax"]) {
            const $ = cheerio.load(html);
            //我只需要一小段html 基础的核心原理
            ctx.body = $("#js-hooks-data").html();
            // ctx.body = {
            //     html:$("#js-hooks-data").html(),
            //     css: <!-- injectcss -->,
            //     js: <!-- injectjs -->
            // } 
            //CSR方式
            //ctx.body = "<x-add></x-add>"
        } else {
            ctx.body = html;
        }
    }
    @route("/create")
    @GET()    
    actionCreate() {
        return async (ctx, next) => {
            const html = await ctx.render("books/pages/add");            
            if (ctx.request.header["x-pjax"]) {
                const $ = cheerio.load(html);
                let _result = "";
                $(".pjaxcontent").each(function() {
                    _result += $(this).html();
                });
                console.log("_result", _result)
                $(".lazyload-css").each(function() {
                    _result += $(this).html()
                });
                $(".lazyload-js").each(function() {
                    // _result += `<script src="${$(this).attr("src")}"></script>`
                    _result = `<script>${$(this).attr("src")}</script>`
                });
                ctx.body = _result;
            } else {
                ctx.body = html;
            }
            
        }
    }
    @route("/savedata")
    @GET()    
    actionSaveData() {
        return async (ctx, next) => {
            const params = new URLSearchParams();
            params.append("Books[title]", "测试的书名");
            params.append("Books[author]", "测试作者");
            params.append("Books[publisher]", "测试出版社");
            const result = await this.bookService.saveData({
                params
            });
            ctx.body = result;
        }
    }
}
module.exports = BooksController;

二、生成接口文档

npm install jsdoc --save # 安装jsdoc

# 在package.json文件中配置docs
"docs": "jsdoc ./**/*.js -d ./docs/jsdocs"

三、项目命令:

  "scripts": {
    "test": "echo $npm_package_config_port",
    "server:dev": "scripty",
    "server:prod": "scripty",
    "server:lint": "scripty",
    "dev": "cross-env NODE_ENV=development supervisor ./dist/app.js",
    "docs": "jsdoc ./**/*.js -d ./docs/jsdocs",
    "client:dev": "webpack --mode development",
    "clinet:prod": "webpack --mode production",
    "build": "babel"
  },

scripty的使用,新建scripts目录,在scripts中新建server目录,以dev为例,我们建dev.sh文件,然后写入cross-env NODE_ENV=development gulp命令

四、package.json中的钩子

package.json 前加pre会先执行(如pretest),再执行test
package.json钩子 husky插件

curl -H 'Content-Type:application/json' 'http://localhost/index.php?r=userinfo/create' -d '{"name":"张六","sex":1,"age":29,"user_id":1078}'

上一篇 下一篇

猜你喜欢

热点阅读