npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

txk-mvc

v1.0.141

Published

基于NodeJS的轻量级MVC微服务框架

Downloads

209

Readme

txk-mvc 一个基于NodeJs的MVC微服务框架

定义

txk-mvc是一个基于NodeJs的微服务MVC框架。 我的名字全拼是tangxuke,因此使用txk-mvc作为框架名字。

设计思想

txk-mvc框架用于快速开发一个具有基本MVC三层架构的微服务,利用此框架开发出来的微服务,可独立运行服务,也可以无缝注册到以此框架开发的微服务注册中心。

如何使用(以下例子将示范如何利用txk-mvc开发一个微服务)

首先,创建一个目录,以myapp为例

mkdir myapp
cd myapp

初始化npm

npm init

保持默认选项或者根据需要修改即可。

引入txk-mvc框架

npm i txk-mvc -s

如果之前使用了txk-mvc低版本,必须升级到最新的版本

npm update txk-mvc

txk-mvc包含了以下基础的类库,用户必须继承这些基类并实现其中一些配置,利用这些类可以方便的创建自己的微服务:

BaseController: 控制器原型
BaseRequest:    请求验证原型
BaseService:    服务原型
BaseValidator:  验证器原型
AllValidators:  内置几个验证器(必填、不能为空、文本长度、正则表达式等几个验证器)
BaseRepository: 数据仓库原型
MySQL:          封装Mysql原型(只有query一个方法)
Redis:          封装Redis原型(高频使用的redis命令封装,如get、set等命令)
BaseApplication:微服务应用原型,由这个对象服务入口,从Koa继承
BaseRegister:   注册中心注册器(将微服务注册到注册中心,或者调用任何注册中心的微服务功能)
MicroRepository:基于微服务的数据仓库原型,调用的是微服务的方法,而不是实体mysql或redis的物理命令

示范(一个提供mysql功能的微服务)

app.js

const { MyApplication } = require('txk-service')
const config = require('./config')
const router = require('./router')

class MySqlApplocation extends MyApplication {
    getName() {
        return config.app_name
    }
    getPort() {
        return config.app_port
    }
    getDesc() {
        return config.app_desc
    }
    getServiceUrl() {
        return config.service_url
    }
}

const app = new MySqlApplocation(router)
app.listen()

说明:txk-service是对txk-mvc的一个默认封装,包括一个注册器和一个应用对象

运行的效果:

node app.js

生产环境使用:

pm2 start app.js -i max
PS D:\GitHub\stall\micro-services\mysql-service-read> node app.js
mysql-stall-read stall mysql 微服务(主读) 正在监听端口 20101
本地测试地址: http://localhost:20101
公开访问地址: https://xxx.cn/service/mysql/stall/read
已经登记到注册中心
已经更新微服务列表
最新微服务列表如下:
-----------------------------------------
[ { app: 'mysql-stall-master',
    url: 'https://xxx.cn/service/mysql/stall/write' },
  { app: 'mysql-stall-write',
    url: 'https://xxx.cn/service/mysql/stall/write' },
  { app: 'redis-master',
    url: 'https://xxx.cn/service/redis/write' },
  { app: 'redis-slave',
    url: 'https://xxx.cn/service/redis/read' },
  { app: 'mysql-stall-read',
    url: 'https://xxx.cn/service/mysql/stall/read' } ]
-----------------------------------------
注册成功!

config.js 配置文件

module.exports = {
    mysql_host: '127.0.0.1',
    mysql_port: 3306,
    mysql_user: 'root',
    mysql_password: '123456',
    mysql_database: 'stall',
    app_port: 20101,
    app_name: 'mysql-stall-read',
    app_desc: 'stall mysql 微服务(主读)',
    service_url: 'https://xxx.cn/service/mysql/stall/read'
}

router.js 路由文件

const Router = require('koa-router')
const Controller = require('./controller')

module.exports = new Router()
    .post('/query', ctx => new Controller(ctx).query())

request.js 请求验证器

const { BaseRequest, AllValidators } = require('txk-mvc')

class Request extends BaseRequest {
    query() {
        return this.use('body', 'sql', new AllValidators.NotEmptyValidator()).check()
    }
}

module.exports = Request

请求验证器主要由use方法和check方法。 use方法用于加载验证器,可通过链式调用加载多个验证器。 check方法用于返回验证结果给到控制器,返回格式:

{
    result:boolean,
    code:number,
    msg:string,
    data:{
        query:any,
        body:any,      
        params:any,
        headers:any
    }
}

service.js 服务对象

const { BaseService } = require('txk-mvc')
const MySql = require('./mysql')     //对mysql原型的默认封装

class MySqlService extends BaseService {
    query() {
        return new MySql().query(this.request.body.sql, this.request.body.params)
    }
}

module.exports = MySqlService

mysql.js 对mysql基类的进行具体的配置

const { MySQL } = require('txk-mvc')
const config = require('./config')

class DefaultMySql extends MySQL {
    getHost() {
        return config.mysql_host
    }
    getPort() {
        return config.mysql_port
    }
    getUser() {
        return config.mysql_user
    }
    getPassword() {
        return config.mysql_password
    }
    getDatabase() {
        return config.mysql_database
    }
}

module.exports = DefaultMySql

controller.js 控制器

const { BaseController } = require('txk-mvc')
const Request = require('./request')
const Service = require('./service')

class Controller extends BaseController {
    async query() {
        let request = await new Request(this.ctx).query()
        if (!request.result) {
            return this.error(request.code, request.msg)
        }

        let result = await new Service(request.data).query()

        return this.success(result)
    }
}

module.exports = Controller

调用微服务测试:

a.js

const { MyRegister } = require('txk-service')
new MyRegister().getService('mysql-stall-read', 'query', {
    sql: 'select * from user'
}).then(value => {
    console.log(value)
}).catch(reason => {
    console.log(reason.message)
})

输出:

PS D:\GitHub\stall\api> node a.js
[ { id: 7,
    openid: 'oGNfy5Bit3kugmizUR2rjvvloL_Y',
    nickName: '唐旭克',
    avatarUrl:
     'https://wx.qlogo.cn/mmopen/vi_32/4FYsd8bWiaR9FfnQ950s9ViaSjsCXKpvkpEgESjfMebUL7ibvqhDguttQsKd255fNLYiaV4gKTXHOs4AbN8eKcNIuA/132',
    userid: '',
    city: 'Dongguan',
    province: 'Guangdong',
    country: 'China',
    gender: 1,
    language: 'zh_CN' } ]
PS D:\GitHub\stall\api>

参数验证不通过的示范: a.js

const { MyRegister } = require('txk-service')
new MyRegister().getService('mysql-stall-read', 'query', {
    sql1: 'select * from user'     //参数错误
}).then(value => {
    console.log(value)
}).catch(reason => {
    console.log(reason)
})

输出:

PS D:\GitHub\stall\api> node a.js
{ code: 1001, msg: 'sql 字段内容为空!' }
PS D:\GitHub\stall\api> 

txk-service源码,目的是设置项目公共的注册中心地址,并设置应用类的默认注册中心

const { BaseRegister, BaseApplication } = require('txk-mvc')

class MyRegister extends BaseRegister {
    getMasterRedis() {
        return 'https://xxx.cn/service/redis/write'
    }
    getSlaveRedis() {
        return 'https://xxx.cn/service/redis/write'
    }
}

class MyApplication extends BaseApplication {
    getRegister() {
        return new MyRegister()
    }
}

module.exports = {
    MyRegister, MyApplication
}