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

@wangminghua/koa-restful

v1.0.13

Published

Koa Restful 是一个基于 Koa 框架的 Restful Web API 插件开源库,使用 TypeScript 构建。它旨在提供一种轻量、高效、易用的方式来构建 RESTful 风格的后端服务。

Downloads

18

Readme

koa-restful

Koa Restful 是一个基于 Koa 框架的 Restful Web API 插件开源库,使用 TypeScript 构建。它旨在提供一种轻量、高效、易用的方式来构建 RESTful 风格的后端服务。

Contributors Forks Stargazers Issues

上手指南

依赖

npm install reflect-metadata koa @wangminghua/koa-restful typescript

开发前的配置要求

  1. Node 版本要求 >= 16
  2. 项目源码必须使用 typescript 编写,并设置 tsconfig.jsoncompilerOptions.experimentalDecoratorscompilerOptions.emitDecoratorMetadatatrue

运行仓库 demo

# 克隆源码仓库
git clone https://github.com/WangMingHua111/koa-restful.git

# 进入工作目录
cd koa-restful

# npm插入依赖
npm install

# 构建dist、dist-example、README.md
npm run build-all

# 运行示例
npm run run-simple

工程创建

创建工程目录

# 你的工程名称
mkdir simple-api
# 进入项目目录
cd simple-api
# npm 初始化,执行npm初始化流程
npm init
# 安装 koa 和 koa-restful
npm install reflect-metadata koa @wangminghua/koa-restful typescript
# 执行typescript配置文件初始化
npx tsc --init

工程模板(快速启动器)

koa-restful-quick-start

在线测试

传送门 koa-restful-quick-start 在线测试

传送门

QQ 交流群

QQ交流群

示例代码

src-example\simple.ts 常用示例

// src-example/simple.ts
import { Controller, FromBody, FromHeader, FromQuery, FromRoute, HttpDelete, HttpGet, HttpHead, HttpPatch, HttpPost, HttpPut, KoaRestful } from '@wangminghua/koa-restful'
import Koa, { Context } from 'koa'

// 测试类型
type TestModel = { name: string; value: string }

// 创建 GET 请求控制器(仅支持类)
@Controller()
class GetController {
    // 返回一个字符串
    @HttpGet()
    test1(): string {
        return `GetController test1 = ${new Date().toLocaleTimeString()}`
    }

    // 获取查询参数
    @HttpGet()
    test2(@FromQuery() name: string): string {
        return `GetController test2 = ${new Date().toLocaleTimeString()} name = ${name}`
    }

    // 获取路径参数
    @HttpGet('test3/:id')
    test3(@FromRoute() id: string): string {
        return `GetController test3 = ${new Date().toLocaleTimeString()} id = ${id}`
    }

    // 读取路径参数和查询参数
    @HttpGet('test4/:id')
    test4(@FromRoute() id: string, @FromQuery() name: string): string {
        return `GetController test4 = ${new Date().toLocaleTimeString()} id = ${id} name = ${name}`
    }

    // 第一个参数默认为Koa Context
    @HttpGet('test5/:id')
    test5(ctx: Context, @FromRoute() id: string, @FromQuery() name: string): string {
        return `GetController test5 = ${new Date().toLocaleTimeString()} id = ${id} name = ${name} ip = ${ctx.request.ip}`
    }

    // 方法参数名称不匹配时,指定从固定参数读取
    @HttpGet('test6/:id')
    test6(@FromRoute('id') id2: string): string {
        return `GetController test6 = ${new Date().toLocaleTimeString()} id = ${id2}`
    }

    // 从请求头读取token参数
    @HttpGet()
    test7(@FromHeader() token: string): string {
        return `GetController test7 = ${new Date().toLocaleTimeString()} token = ${token}`
    }
    // 强制路由转换 为 test8-2
    @HttpGet('test8-2')
    test8(): string {
        return `GetController test8 = ${new Date().toLocaleTimeString()}`
    }
}

// 创建 其他类型 请求控制器(仅支持类), 路由参数、查询参数、请求头参数使用方法于GetController一致
@Controller()
class OtherController {
    // 返回一个字符串 /other/test1
    @HttpPost()
    test1(): string {
        return `GetController test1 = ${new Date().toLocaleTimeString()}`
    }
    // 返回修改过的TestModel /other/test2
    @HttpPost()
    test2(@FromBody() body: TestModel): TestModel {
        body.name += '-back'
        body.value += '-back'
        return body
    }

    // 一个方法同时支持多种类型的请求 /other/test3
    @HttpGet()
    @HttpPost()
    @HttpDelete()
    @HttpPatch()
    @HttpHead()
    @HttpPut()
    test3(): TestModel {
        return { name: 'n1', value: 'n2' }
    }
}

// 创建 其他类型 请求控制器(仅支持类), 路由参数、查询参数、请求头参数使用方法于GetController一致
// 指定控制器路由
@Controller('api/other')
class Other2Controller {
    // 返回一个字符串 /api/other/test1
    @HttpPost()
    test1(): string {
        return `Other2Controller test1 = ${new Date().toLocaleTimeString()}`
    }
    // 指定方法路由为 /api/other/t
    @HttpPost('t')
    test2(): string {
        return `Other2Controller test1 = ${new Date().toLocaleTimeString()}`
    }
}

const app = new Koa()
app.use(KoaRestful({ logs: true })) // 使用 KoaRestful 插件
app.listen(3000) // 创建 http://localhost:3000

console.log('启动成功,3秒后执行 restful api 请求。')
console.log('http://localhost:3000')

src-example\di.ts 依赖注入示例

import { Controller, Dependency, HttpGet, Injection, KoaRestful, ResolveDependency, ResolveDependencyFromUniqueId } from '@wangminghua/koa-restful'
import Koa from 'koa'

interface IDep {
    val(): number
}

abstract class Dep {
    constructor() {}
    abstract val(): number
}

// 声明一个依赖
// 等效于 AddDependency(new DepImpl(), { alias: [Dep], uniqueId: 'DepImpl' }) , AddDependency 不支持singleton
@Dependency({ alias: [Dep], lifecycle: 'singleton', uniqueId: 'DepImpl' })
class DepImpl extends Dep {
    val(): number {
        return Date.now()
    }
}

// 创建 GET 请求控制器(仅支持类)
@Controller()
class GetController {
    // 注入DepImpl
    @Injection()
    dep1!: DepImpl
    // 注入抽象类Dep
    @Injection()
    dep2!: Dep
    // 通过uniqueId查找对象注入IDep
    @Injection({ uniqueId: 'DepImpl' })
    dep3!: IDep

    // 解析依赖DepImpl
    dep4 = ResolveDependency(DepImpl)
    // 解析依赖Dep
    dep5 = ResolveDependency(Dep)
    // 通过uniqueId,解析依赖IDep
    dep6 = ResolveDependencyFromUniqueId<IDep>('DepImpl')
    // 返回一个字符串
    @HttpGet()
    test1(): string {
        const arr: Array<IDep | undefined> = [this.dep1, this.dep2, this.dep3, this.dep4, this.dep5, this.dep6]
        arr.forEach(console.log) // 日志输出注入/解析对象
        return `GetController test1 = ${new Date().toLocaleTimeString()}`
    }
}

const app = new Koa()
app.use(KoaRestful({ logs: true })) // 使用 KoaRestful 插件
app.listen(3000) // 创建 http://localhost:3000

console.log('启动成功,3秒后执行 restful api 请求。')
console.log('http://localhost:3000')