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

koa-tiny

v1.1.0

Published

A simple node service framework

Downloads

152

Readme

Tiny

Introduction

  • 简体中文

  • Tiny is a simple server-side tool library based on Node+Typescript+Koa2/ecosystem, with core code of less than 20K. It provides many interesting classes and decorators that can help you save time on configuring routes, validating parameters, setting login states, writing API documentation, and other additional functionalities.

  • Tiny aims to provide a simple tool library for developers, without involving deployment or operational content.

Environment

NODE Version NPM Version

Directory

Installation

  • Before installation, please download and install Node.js. Node.js version 16.0.0 or higher is required.

Creating a Tiny Application

  • You can create a project based on Tiny using the project template provided by Tiny, which sets up a simple project structure for your reference.
npm create koa-tiny <project-name>

Install Tiny in an existing project

npm install --save koa-tiny

View current API information

  • If the project is built using Tiny templates, you can access/doc.htmlthe address to view the simplest API information

Usage

First-time usage example

  • Fileindex.ts
import Tiny, { Controller } from 'koa-tiny';
import Koa from 'koa';
import Router from '@koa/router';
import { Manager } from '@/controller/manager';

const app = new Koa();
const router = new Router();

// 初始化配置
Tiny.init({
  controller: { prefix: '/api/' },
  jwt: { expiresIn: '4h', jsonwebtoken: jsonwebtoken }
});

// 连接你的控制器
Controller.connect<Manager>(new Manager(), router);

app.listen(4000);
  • File@/controller/manager.ts
import { Json, Summary, Dto, StatusCode, Get } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

export class Manager {
  @Get()
  @Json()
  @Summary('This is a summary')
  public async index(ctx: ExtendableContext, next: Next) {
    ctx.body = new Dto({ code: StatusCode.success, result: 'hello word', msg: 'success' });
    return next();
  }
}
  • InitOptionsParameter description
interface InitOptions {
  // 控制器配置参数
  controller?: ControllerOptionsInput;
  // jwt配置参数
  jwt?: JwtOptionsInput;
}
  • For configuration information of ControllerOptionsInput, see:Controller
  • For configuration information of JwtOptionsInput, see:Jwt

API Description

Controller

Controller

  • UsageController.connect<T>(instance: T, router: Router)Controller class for connecting to the system
// 连接你的控制器
Controller.connect<Manager>(new Manager(), router);
  • UsageController.options: ControllerOptionsInputGet controller configuration items
// 打印配置
console.log(Controller.options)

// 配置类型
type ControllerOptionsInput = {
  // API前缀-全局,默认:''
  prefix?: string;
  // 是否是驼峰,默认:false
  hump?: boolean;
};
  • UsageController.apiInfoJsonGet JSON information of the API
// 打印JSON信息
console.log(Controller.apiInfoJson)
  • UsageController.jwtProtectedListGet the list of routes protected by JWT
// 打印列表信息
console.log(Controller.jwtProtectedList)

Get

  • Usage@Get()Decorator to declare a Get method
import { Get } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

export class Manager {
  @Get()
  public async index(ctx: ExtendableContext, next: Next) {
    // ...
  }
}

Delete

  • Usage@Delete()Decorator to declare a Delete method
import { Delete } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

export class Manager {
  @Delete()
  public async index(ctx: ExtendableContext, next: Next) {
    // ...
  }
}

Post

  • Usage@Post()Decorator to declare a Post method
import { Post } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

export class Manager {
  @Post()
  public async index(ctx: ExtendableContext, next: Next) {
    // ...
  }
}

Put

  • Usage@Put()Decorator to declare a Put method
import { Put } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

export class Manager {
  @Put()
  public async index(ctx: ExtendableContext, next: Next) {
    // ...
  }
}

View

  • Usage@View()Decorator to declare a View method
import { View } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

export class Manager {
  @View()
  public async index(ctx: ExtendableContext, next: Next) {
    // ...
  }
}

Json

  • Usage@Json(handler?: Router.Middleware)Decorator, declare the data type of the Body
import { Post, Json } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

export class Manager {
  @Post()
  @Json()
  public async index(ctx: ExtendableContext, next: Next) {
    // ...
  }
}

Text

  • Usage@Text(handler?: Router.Middleware)Decorator, declare the data type of the Body
import { Post, Text } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

export class Manager {
  @Post()
  @Text()
  public async index(ctx: ExtendableContext, next: Next) {
    // ...
  }
}

FormUrlencoded

  • Usage@FormUrlencoded(handler?: Router.Middleware)Decorator, declare the data type of the Body
import { Post, FormUrlencoded } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

export class Manager {
  @Post()
  @FormUrlencoded()
  public async index(ctx: ExtendableContext, next: Next) {
    // ...
  }
}

FormData

  • Usage@FormData(handler?: Router.Middleware)Decorator, declare the data type of the Body
import { Post, FormData } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

export class Manager {
  @Post()
  @FormData()
  public async index(ctx: ExtendableContext, next: Next) {
    // ...
  }
}

Other

  • Usage@Other(handler?: Router.Middleware)Decorator, declare the data type of the Body
import { Post, Other } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

export class Manager {
  @Post()
  @Other()
  public async index(ctx: ExtendableContext, next: Next) {
    // ...
  }
}

Prefix

  • Usage@Prefix(text: string)Decorator, set the prefix for a single route
import { Post, Prefix } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

export class Manager {
  @Post()
  @Prefix('/test/')
  public async index(ctx: ExtendableContext, next: Next) {
    // ...
  }
}

Mapping

  • Usage@Mapping(path: string)Decorator, reset the route address
import { Post, Prefix } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

export class Manager {
  @Post()
  @Prefix('/manager/test/:id')
  public async index(ctx: ExtendableContext, next: Next) {
    // ...
  }
}

Summary

  • Usage@Summary(text: string)Decorator, set the description for the method
import { Post, Summary } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

export class Manager {
  @Post()
  @Summary('测试方法')
  public async index(ctx: ExtendableContext, next: Next) {
    // ...
  }
}

Model

Model

  • Usagemodel<Model>.fill(map: object)Fill data model
class LoginInput extends Model {
  @Declare()
  name!: string;

  @Declare()
  password!: string;
}

const input = new LoginInput();
const result: ModelResult = input.fill({...});
if(result.valid) {
  // ...
}
  • Usagemodel<Model>.getConfigCacheGet current model configuration
const input = new LoginInput();
console.log(input.getConfigCache())
ModelResult
  • Usagenew ModelResult(valid: boolean, message?: string, value?: any)Set model validation result

Declare

  • Usage@Declare(description?: string)Decorator, declare parameters, note: model parameters must be used at leastDeclare
class LoginInput extends Model {
  @Declare()
  name!: string;
}

Required

  • Usage@Required(message?: string)Decorator, set properties must
class LoginInput extends Model {
  @Declare()
  @Required('名称不能唯空')
  name!: string;
}

TypeCheck

  • Usage@TypeCheck(type: ParamsType | T, message?: string)Decorator, set type checking
class LoginInput extends Model {
  @Declare()
  @TypeCheck(ParamsType.string, '名称只能为字符串')
  name!: string;
}

ArrayCheck

  • Usage@ArrayCheck(type: ParamsType | T, message?: string, maxLength?: number)Decorator, set array type checking, precondition isTypeCheckSetParamsType.array
class LoginInput extends Model {
  @Declare()
  @TypeCheck(ParamsType.array, '列表只能为数组')
  @ArrayCheck(ParamsType.string, '数组内容只能为字符串')
  list!: string[];
}

StringLength

  • Usage@StringLength(range: number[], message?: string)Decorator, set string length validation, precondition isTypeCheckSetParamsType.string
class LoginInput extends Model {
  @Declare()
  @TypeCheck(ParamsType.string, '名称只能为字符串')
  @StringLength([1,50], '名称长度只能为1-50')
  name!: string;
}

Params

Params

  • Usage@Params<T extends Model>(params: { new (): T }, type: ParamsSource, validate: boolean = true, handler?: <P1, P2>(p1: P1, p2: P2) => T)Decorator, set input parameter validation
import { Post, Params } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

class LoginInput extends Model {
  @Declare()
  name!: string;

  @Declare()
  password!: string;
}

export class Manager {
  @Post()
  @Params(LoginInput, ParamsSource.body)
  public async index(ctx: ExtendableContext, next: Next, extend: DtoCtxExtend<LoginInput, null>) {
    console.log(extend.params.name)
    console.log(extend.params.password)
    // ...
  }
}

Result

  • Usage@Result<T extends Model>(result: { new (): T })Decorator, set output parameter type
import { Post, Params, Dto, StatusCode } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';

class LoginOut extends Model {
  @Declare()
  id!: string;

  @Declare()
  name!: string;
}

export class Manager {
  @Post()
  @Result(LoginOut)
  public async index(ctx: ExtendableContext, next: Next) {
    // ...
    const info = new LoginOut();
    info.fill({...});
    ctx.body = new Dto({ code: StatusCode.success, result: info, msg: 'success' });
  }
}

Jwt

Jwt

  • UsageJwt.sign<T>(ctx: ExtendableContext, payload: T)Generate token
Jwt.sign<JwtPayload>(ctx, {...});
  • UsageJwt.verify<T>(ctx: ExtendableContext): T | nullValidate token
const payload = Jwt.verify(ctx);
  • UsageJwt.optionsGet controller configuration items
// 打印配置
console.log(Jwt.options)

// 配置信息
type JwtOptionsInput = {
  // jsonwebtoken类,详见:https://github.com/auth0/node-jsonwebtoken
  jsonwebtoken: {
    verify: Function;
    sign: Function;
  };
  // 私钥key,默认:'shared-secret'
  privateKey?: string;
  // 算法名称,默认:HS256
  algorithms?: string;
  // 过期时间,默认:24h
  expiresIn?: string;
  // 不验证令牌的过期时间,默认:false
  ignoreExpiration?: boolean;
  // 验证不通过返回的错误码,默认:408
  errorCode?: number;
  // 验证不通过返回的错误信息,默认:Unauthorized access
  errorMsg?: string;
  // 保存token的key:'token'
  tokenKey?: string;
  // 自定义获取token的方法
  getToken?: (ctx: ExtendableContext) => string | undefined;
  // 自定义设置token的方法
  setToken?: (ctx: ExtendableContext, value: string) => any;
  // 自定义是否重置token
  isResetToken?: (ctx: ExtendableContext) => boolean;
};

Protected

  • Usage@Protected()Decorator, the configured method will perform JWT validation
import { Post, Protected } from 'koa-tiny';
import { ExtendableContext, Next } from 'koa';
import { YouPayload } from '....'

export class Manager {
  @Post()
  @Protected()
  public async index(ctx: ExtendableContext, next: Next, extend: DtoCtxExtend<null, YouPayload>) {
    console.log(extend.payload)
    // ...
  }
}

Dto

Dto

  • Usagenew Dto({ code: number | string, result?: any, msg?: string })Set Response return code

DtoCtxExtend

  • Usagenew DtoCtxExtend<P1,P2>({ params: P1, payload: P2 })Set ctx additional parameters (for internal use in Tiny)

Values

MethodType

  • Request type
export enum MethodType {
  get = 'get',
  delete = 'delete',
  post = 'post',
  put = 'put',
  view = 'view'
}

DataType

  • Data structure type of the body
export enum DataType {
  json = 'application/json',
  text = 'text/plain',
  formUrlencoded = 'application/x-www-form-urlencoded',
  formData = 'multipart/form-data',
  other = 'other'
}

ParamsSource

  • Parameter source
export enum ParamsSource {
  query = 'query',
  body = 'body'
}

ParamsType

  • Parameter data type
export enum ParamsType {
  number = 'number',
  boolean = 'boolean',
  string = 'string',
  array = 'array'
}

StatusCode

  • Response status value
export const StatusCode = {
  success: 200,
  paramsError: 400,
  authError: 408,
  serveError: 500
};

Others