2.0.5 • Published 5 years ago

jason-api-core v2.0.5

Weekly downloads
-
License
ISC
Repository
-
Last release
5 years ago

#自动创建生成 服务器(mysql)(可视为之前体系 jason-server的未来和持续维护版, 安全性更高, 使用更灵活, 支持打包部署)

注意: 1.避免造成损失不能用于企业应用 2.orderBy较之前略有改动, 数据库操作较之前安全性更高 3.较之前 自动添加事务处理; 为了安全, 身份校验用于自行middleware完成 4.模型方案改变

##特点 1. 自动创建服务,自带mysql服务器连接 方便 2. 自动注入了表的增删改查(如user表)

 findAllUser({filter:{...}, orderBy:{ id: 'DESC', name: 'ASC' }, take: 100, skip: 100})
 findOneUser({filter:{...}})
 createUser({id:...,name:...})
 updateUser({values:{name:...},filter:{id:...}})
 deleteUser(filter)
 countUser(filter)//计数统计,一般用于分页列表

其中filter为过滤条件如:(支持多层嵌套)

{name:'sss',age:89...}// name =’sss‘ and age=89...
{name_ne:'sss',age_gt: 89}//name =’sss‘ and age>89
{name_ne:'sss',age_gte: 89}//name =’sss‘ and age>=89
{name_like:'sss%',age_lt:89}//name like ’sss‘ and age<89
{name_like:'sss%',age_lte:89}//name like ’sss‘ and age<=89
{name_notLike:'%sss'}//name not like ’sss‘ 
{name_in:['sss']}//name in [’sss‘] 
{name_notIn:['sss']}//name not in [’sss‘ ]
{
  AND:[
    {name:'99'},
    {id_ne:'1111'},
    ...
  ]
 }// name='99' and id != '1111'...
 {
  OR:[
    {name:'99'},
    {id_ne:'1111'},
    ...
  ]
 }//name ='99' or id != '1111'...

等等... #如何使用
1. 数据库表: 在XXX目录下创建表文件目录,在目录下创建表文件 Test.sql

create Table @Test@ (
  id varchar(50) primary key,
  name varchar(100),
  updateTime dateTime,
  createTime dateTime not null
)// 必须含有 updateTime createTime id 三个字段

2.package.json 脚本

"scripts": {
    //执行脚本 自动生成api导出文件 导出在当前工作目录下的/src/api目录下
    //model_dir: model文件夹名 api_dir:  自定义api文件夹名
    "init": "model_dir=model api_dir=api-server babel-node ./src/init-api/index.js",
    // 创建表: 会删掉原来的表
    "init-table": "model_dir=model babel-node ./src/init-api/init-table.js",
    "dev": "babel-node ./src/index.js", // 第一次先执行 init
    "build": "NODE_ENV=production webpack"
  },

./src/init-api/init-table.js 文件

import { initTable } from 'jason-api-core'
import { getConnection } from '../util'

const createTable = async () => {
  const conn = await getConnection()
  initTable(conn)
}

createTable()

./src/init-api/index.js 文件

import { initCustomApi, initApi, initModel } from 'jason-api-core'

initCustomApi(() => {
  console.log('CUSTOM API IS WRITED!')
})

initModel(() => {
  console.log('MODEL API IS WRITED!')
})

initApi()

##第一种方案

###创建服务

iimport express from 'express'
import 'babel-polyfill'
import bodyParser from 'body-parser'
import cors from 'cors'
import { matchApiMiddleware } from './middlewares' // 用户自定义

const app = express()
app.use(cors())
app.use(bodyParser.json({ limit: '50mb' }))
app.use(bodyParser.urlencoded({ extended: true }))
app.use(matchApiMiddleware)

app.listen(8080, () => {
  console.log('SERVER IS RUNNING IN OPRT 8080')
})

其中 matchApiMiddleware 为用户自定义 根据实际情况写 例如:

import { mathApiMiddleware } from 'jason-api-core'
import { getConnection } from '../util'
import apiServiers from '../api' // npm run init 生成的目录文件导出api

export default async (req, res) => {
  const conn = await getConnection() // mysql 连接
  return mathApiMiddleware(conn, apiServiers)(req, res)
}

##写自定义接口

import {inject, apiService} from 'jason-api-core'
//登录
export const login = apiService(
    inject([
      'findOneAccount', 'findOneUser', 'findOneToken', 'createToken', 
      'updateToken', 'updateAccount'
    ]),
)(async ({findOneAccount, findOneUser, findOneToken, createToken, updateToken, updateAccount}, {mobile, password}) => {

    const account = await  findOneAccount({mobile, password: hasMd5(password)});
    if (!account) return {error: '账号不存在或密码错误'};
    const accountId = account.id;
    const user = await  findOneUser({accountId});
    if (!user) return {error: '用户不存在'}
    await updateAccount({account: {lastLoginTime: formatDateTime(new Date())}, filter: {id: accountId}})
    let token = await  findOneToken({accountId}) || await  createToken({accountId});
    await updateToken({token, filter: {id: token.id}});

    return {user, accountId, tokenId: token.id}
})
login 接口名
inject:引入其他接口,包括自定义和系统自定义

##第二种方案(伪class) 该方案主要用于过度,非真正的class, 后续还会提供真正的class api方案 ###创建服务

import express from 'express'
import 'babel-polyfill'
import bodyParser from 'body-parser'
import cors from 'cors'
import { getConnection } from '../util' // mysql 连接
import modelServer from '../api/model' // npm run init 生成文件
import customServer from '../api/custom' // npm run init 生成文件
import { mathApiMiddleware } from 'jason-api-core'


const app = express()
app.use(cors())
app.use(bodyParser.json({ limit: '50mb' }))
app.use(bodyParser.urlencoded({ extended: true }))
app.use(async (req, res) => {
  const conn = await getConnection()
  const options = {
    modelServer,
    customServer,
    useClassApi: true
    } // useClassApi 使用class方式
  mathApiMiddleware(conn, options)(req, res)
})

app.listen(8080, () => {
  console.log('SERVER IS RUNNING IN OPRT 8080')
})

###写自定义接口

import { Inject } from 'jason-api-core'

export class User {

  @Inject(['deleteUsers']) // 引入另外的接口
  async getUsers ({ deleteUsers }, values) { // getUsers 全局不能重复
    return await deleteUsers(values)
  }

  @Inject(['findAllUser']) // 引入系统根据model内置接口
  async deleteUsers ({ findAllUser }, values) {
    return await findAllUser({...})
  }
}

##第三种方案(真class) 真实class方式, 和一二方案完全不同 注意如下: 1. 不需先跑 npm run init 2. 模拟java的 controller serveice dao 三层结构 分工明确,层次清晰 3. 与模型model文件夹无关

dto配置

import { initDTOFromArray, createTableFromArray } from 'jason-api-core'

const DTOS = [
{
 name: 'User',
 keys: [
   { name: 'id', type: 'VARCHAR', length: '50', key: true, none: false },
   { name: 'name', type: 'VARCHAR', length: '50' },
   { name: 'age', type: 'INT', length: '4' },
   { name: 'createTime', type: 'DateTime', none: false },
   { name: 'updateTime', type: 'DateTime' },
 ]
},
{
 name: 'Account',
 keys: [
   { name: 'id', type: 'VARCHAR', key: true, none: false },
   { name: 'userId', type: 'VARCHAR', none: false },
   { name: 'createTime', type: 'DateTime', none: false },
   { name: 'updateTime', type: 'DateTime' },
 ]
}
]

//  自动创建表
createTableFromArray(DTOS, conn) // conn mysql连接

// 初始化成dto类型
initDTOFromArray(DTOS, '/src/dto')

// 生成文件 User.js
export class Account {
constructor(id, userId, createTime, updateTime) {
 this.id = id
 this.userId = userId
 this.createTime = createTime
 this.updateTime = updateTime
}
setId (id) {
 this.id = id
}

getId () {
 return this.id
}

setUserId (userId) {
 this.userId = userId
}

getUserId () {
 return this.userId
}

setCreateTime (createTime) {
 this.createTime = createTime
}

getCreateTime () {
 return this.createTime
}

setUpdateTime (updateTime) {
 this.updateTime = updateTime
}

getUpdateTime () {
 return this.updateTime
}

}

创建服务

import express from 'express'
import 'babel-polyfill'
import bodyParser from 'body-parser'
import cors from 'cors'
import { mathApiMiddleware } from 'jason-api-core'
import * as DTOS from './UserController' // 此处应该为所有的接口类集合


const app = express()
app.use(cors())
app.use(bodyParser.json({ limit: '50mb' }))
app.use(bodyParser.urlencoded({ extended: true }))
app.use(async(request, response) => {
   const connection = await getConnection() // 数据库的连接
   mathApiMiddleware({
    request, 
    response,
    connection,
    classes: DTOS
  })
}) //  配置信息

app.listen(8080, () => {
  console.log('SERVER IS RUNNING IN OPRT 8080')
})

结构层次

controller 文件夹

import { RequestMapping, Autoware } from 'jason-api-core'

import { UserService } from './UserService'

@RequestMapping('user') // 路由
@Autoware(UserService, 'userService') // 注入外部引入service(userService 可省略)
export class UserController {

  getUsers (values) {
    return this.userService.getServerUsers()
  }
}

service 文件夹

import { Autoware } from 'jason-api-core'
import { UserDao } from './UserDao'

@Autoware(UserDao)
export class UserService {

  getServerUsers () {
    console.log('this is User service')
    return this.userDao.testDao()
  }
}

dao 文件夹

import { AutowareModel } from 'jason-api-core'

@AutowareModel('User')
export class UserDao {

  async testDao (connction) {
    const params = {
      filter: {
        // name_like: '%vhjb%'
      },
      orderBy: {
        createTime: 'DESC',
        name: 'ASC'
      },
      take: 100
    }
    const user = await this.createUser({ name: Math.random().toString() }, connction)
    const u = await this.findOneUser({ id: user.id }, connction)
    const u1 = await this.updateUser({ values: { name: 1111 }, filter: { id: u.id } }, connction)
    const users = await this.findAllUser(params, connction)
    const count = await this.countUser({}, connction)
    console.log(u, u1)
    return {
      count,
      users
    }
  }
}
2.0.5

5 years ago

2.0.4

5 years ago

2.0.3

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.3.2

5 years ago

1.3.1

5 years ago

1.3.0-test-03

5 years ago

1.3.0-test-02

5 years ago

1.3.0-test-01

5 years ago

1.3.0

5 years ago

1.2.12-test-02

5 years ago

1.2.12-test-01

5 years ago

1.2.12-test

5 years ago

1.2.11

5 years ago

1.2.10

5 years ago

1.2.9

5 years ago

1.2.8

5 years ago

1.2.7

5 years ago

1.2.6

5 years ago

1.2.5

5 years ago

1.2.4

5 years ago

1.2.3

5 years ago

1.2.2

5 years ago

1.2.1

5 years ago

1.2.0

5 years ago

1.1.2

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago