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 🙏

© 2024 – Pkg Stats / Ryan Hefner

jason-api-core

v2.0.5

Published

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

Downloads

11

Readme

#自动创建生成 服务器(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
    }
  }
}