egg-atlas-framework
TypeScript icon, indicating that this package has built-in type declarations

1.4.8 • Public • Published

egg-atlas-framework

  • 该框架封装的目的是减少部分开发工作
  • 数据库使用mongodb,插件使用mongoose
  • 响应内容为json数据
  • 友好的错误处理
  • 集成部分工具类,方便使用
  • 建议使用ts开发,提示难受呀

QuickStart

$ npm install egg-atlas-framework

package.json:

{
    "egg": {
      "declarations": true,
      "framework": "egg-atlas-framework"
    }
}

default plugins

    nunjucks: {
        enable: true,
        package: 'egg-view-nunjucks'
    },
    validate: {
        enable: true,
        package: 'egg-validate',
    },
    mongoose: {
        enable: true,
        package: 'egg-mongoose',
    },
    passport: {
        enable: true,
        package: 'egg-passport'
    },
    sessionMongo: {
        enable: false,
        package: 'egg-session-mongo',
    },
    passportLocal: {
        enable: true,
        package: 'egg-passport-local',
    },
    oss: {
        enable: true,
        package: 'egg-oss'
    }

default config

'use strict';

module.exports = appInfo => {
  const baseDir = appInfo.baseDir;
  const path = require('path');
  const config = {};

  /**
   * some description
   * @member Config#test
   * @property {String} key - some description
   */
  config.security = {
    csrf: false
  }
  config.responseTime = {
    enable: true,
    ignore: '/public'
  }
  config.view = {
    root: `${baseDir}/app/public`,
    defaultViewEngine: 'nunjucks',
    mapping: {
      '.tpl': 'nunjucks',
      // '.js': 'assets',
    },
  };
  config.static = {
    prefix: '/',
    dir: path.join(appInfo.baseDir, 'app/public'),
    dynamic: true,
    preload: false,
    maxAge: 31536000,
    buffer: true,
  }
  config.passportLocal = {
    usernameField: 'account',
    passwordField: 'password',
    passReqToCallback: true,
  }
  config.session = {
    renew: true,//session 有效期仅剩一半的时候重置有效期
  }

  return config;
};

default middleware

  • onerror
  • responseTime

Controller

extend methods

    export class Controller extends BaseContextClass{
        serviceName: string;//配置controller对应的serviceName
        body: any;//获取body参数
        query: any;//获取query参数
        params: any;//获取params参数
        se: Service;//调用服务
        success(data?: any): void;//返回{code:1,message:'',data}
        protected getParamsPreproccess(params?: any): void;//get参数预处理
        validate(type: string, params?: any): void;//参数验证 type为rule的名称
        validateWithFields(type: string, fields: string[], params?: any);//参数验证 对某个rule的某些字段进行验证
    }

demo

// controller/home.js
'use strict';

const Controller = require('egg-atlas-framework').Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    this.success(this.query);
  }
}

module.exports = HomeController;


//response 

{
    "code": 1,
    "message": "ok",
    "data": {
        "id": "aaa"
    }
}

Service

extend methods

   export class Service extends BaseContextClass{
        modelBase: string;//mongo model前缀 当前只支持一级,默认没有
        modelName: string;//mongo 对应的modelname
        oss(basePath?: string): string[];//oss上传文件
        wait(ms: number): void;//让系统等待
        populate(path: string, model: any, match?: any, select?: string, modelBase?: string, populate?: any): void;//mongoose populate
        executeTime(actionName: string, start: Date): number;//打印某个动作执行时间
        se(serviceName: string): Service;//调用其他service
        userId: string;//获取当前登录用户id
        user: any;//获取当前登录用户
        systemLog(type: number, content: any, message?: string): void;//记录系统日志到mongodb
        subJson(object: any, fields: string[]): any;//获取某个json对象的子对象
        model: any;//获取当前model
        getModel(modelName: string, modelBase?: string): any;//获取其他model
        get(serverName: string, path: string, params?: any, errorFun?: any): any;//调用get服务
        post(serverName: string, path: string, params?: any, errorFun?: any): any;//调用post服务
        newError(error: DefError): any;//抛出异常
        serverError(message?: string): any;//服务异常
        notFoundError(message?: string): any;//没有找到记录异常
        alreadyExistdError(message?: string): any;//已经存在对象异常
        paramsError(message?: string): any;//参数异常
        notLoginError(message?: string): any;//没有登录
        conflictLoginError(message?: string): any;//被其他登录用户挤下线,一个用户只允许单个对象登录
        timeoutError(message?: string): any;//超时异常
        authError(message?: string): any;//授权异常
        dateUtil: DateUtil;//基于moment封装的工具类
        modelUtil: ModelUtil;//基于mongoose 封装的数据库操作工具类
        _: LodashUtil;//基于lodash 封装的工具类
    }

demo ts版本

import { Service } from 'egg-atlas-framework';

/**
 * Test Service
 */
export default class Test extends Service {

  public static abc: string;
  /**
   * sayHi to you
   * @param name - your name
   */
  public async sayHi(name: string) {
    const now = this.dateUtil.getNowDate('LL');
    this.logger.info(now);
    this.logger.info(this.dateUtil.format2Str('LL'));
    await this.wait(1000);
    return `hi, ${name}`;
  }
}

DateUtil

    export class DateUtil {
        UNITS: UNITS;
        setDate(date: Date): DateUtil;
        getDate(): Date;
        getFormatDate(format?: string): Date;
        getDifferenceDays(date1: Date, date2: Date, format?: string): number;
        getDiffNowDays(date: Date, format?: string): number;
        getNowDate(format?: string): Date;
        parse(dataStr: string, format?: string): DateUtil;
        format2Str(format?: string): string;
        modify(amount: number, unit?: any): DateUtil;
    }

ModelUtil

    export class ModelUtil {
        inc(model: any, conditions: any, field: string, num: number): void;
        deleteMany(model: any, conditions: any): void;
        deleteOne(model: any, conditions: any): void;
        exists(model: any, conditions: any): boolean;
        findOne(model: any, conditions: any,fields: string): any;
        existsError(model: any, conditions: any): void;
        findOneNotThrowErr(model: any, conditions: any,fields: string): any;
        find(model: any, conditions: any, limit?: number, fields?: string, sortBy?: string): any;
        findFieldValues(model: any, conditions: any, limit?: number, field?: string): any[];
        count(model: any, conditions: any): number;
        updateOne(model: any, conditions: any, upsertObj: any, options?: any): any;
        findOneAndUpdate(model: any, conditions: any, upsertObj: any, options?: any): any;
        emptyPage(pageNum?: any, pageSize?: any): any;
        pageWithMemory(model: any, conditions?: any, pageNum?: any, pageSize?: any, fields?: string, populate?: any, sortBy?: string, desc?: boolean): any;
        pageSortNotNull(model: any, conditions?: any, pageNum?: any, pageSize?: any, fields?: string, populate?: any, sortBy?: string): any;
        page(model: any, conditions?: any, pageNum?: any, pageSize?: any, fields?: string, populate?: any, sortBy?: string): any;
    }

params validate

// config/validateRule.ts
export let validateRule = {
    test: {
        id: 'objectId',
    },
    test2: {
        id: 'string',
    },
};
//config/config.default.ts
import { validateRule } from './validateRule';
export default (appInfo: EggAppInfo) => {
  const config = {} as PowerPartial<EggAppConfig>;

  config.validateRule = {
    ...validateRule,
  };
  // ...
  return {
    ...config,
    ...bizConfig,
  };
};

//app/controller/home.ts
import { Controller } from 'egg-atlas-framework';
export default class HomeController extends Controller {
  constructor(ctx) {
    super(ctx);
    this.serviceName = 'test';
  }
  public async index() {
    this.validate('test2', this.query);
    this.success(await this.service.test.sayHi());
  }
}

Questions & Suggestions

微信二维码

Readme

Keywords

Package Sidebar

Install

npm i egg-atlas-framework

Weekly Downloads

4

Version

1.4.8

License

MIT

Unpacked Size

57.8 kB

Total Files

27

Last publish

Collaborators

  • jy