• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

skmdev/koa-decorator-ts: koa decorator

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

skmdev/koa-decorator-ts

开源软件地址:

https://github.com/skmdev/koa-decorator-ts

开源编程语言:

TypeScript 93.6%

开源软件介绍:

koa-decorator-ts

Koa Decorator (with TypeScript)

Installation

npm i koa-decorator-ts --save
/* or */
yarn add koa-decorator-ts

Introduction

This package is a decorator for koa, including the koa-router, graohql. You can use decorators to define the path of routing or create a graphql resolver using existing koa controller

Usage

app.js

import Koa from 'koa';
// 1. Import Router
import Router from 'koa-decorator-ts/router';

const app = new Koa();
// 2. Create router
const router = new Router({
  dir: `${__dirname}/controllers` // The controllers directory
});

// [Optional] Graphql inital
const graphqlServer = new ApolloServer({ schema });
graphqlServer.applyMiddleware({ app });

// 3. Register the routers
app.use(router.routes());
app.use(router.allowedMethods());

...

app.listen(8080);

/controllers/user.ts

import Koa from 'koa';
import {
  Controller,
  Route,
  Middleware,
  Required,
  Graphql,
  Priority,
  Meta,
} from 'koa-decorator-ts';
import { IsString } from 'class-validator';

async function middlewareLog(ctx: Koa.Context, next: Function) {
  await next();
}

//use a class with decorators (class-validator) for validation
class PatchUserRequest{
  @IsString()
  userNickName!:string
  @IsString()
  userAddress!:string
}

// Prefix of api path
@Controller('/user')
class UserController {
  @Priority(-1000)
  @Route.all('*')
  async handleAll(ctx: Koa.Context, next: any) {
    ctx.body = 'haha';
  }

  // Post /user/login
  @Route.post('/login')
  @Required({
    // Require { userEmail, password } in the body
    body: {
      type: 'object',
      properties: {
        userEmail: {
          type: 'string',
        },
        password: {
          type: 'string',
        },
      },
      required: ['userEmail', 'password'],
    },
  })
  async login(ctx: Koa.Context) {
    ctx.body = true;
  }

  // Get /user/:userId
  @Route.get('/:userId')
  @Middleware(middlewareLog) // Add Middleware
  async getUserInfo(ctx: Koa.Context) {
    ctx.body = { userName: 'skm', userEmail: '[email protected]' };
  }

  // Get /user?top=10&star=1000000
  @Route.get('/')
  @Required({
    query: {
      type: 'object',
      properties: {
        top: { type: 'string' },
        star: { type: 'string' },
      },
      required: ['top', 'star'],
    },
  }) // Require for "top", "star" in the query
  @Middleware(middlewareLog)
  async getUsers(ctx: Koa.Context) {
    ctx.body = { userName: 'skm', userEmail: '[email protected]' };
  }

  // Patch /user/:userId
  @Route.patch('/:userId')
  @RequiredBody(PatchUserRequest) //do the same for query using @RequiredQuery
  async updateUserInfo(ctx: Koa.Context) {
    ctx.body = true;
  }

  // Put /user/:userId/follow
  @Route.put('/:userId/follow')
  async followUser(ctx: Koa.Context) {
    ctx.body = true;
  }

  // Delete /user/:userId/follow
  @Route.del('/:userId/follow')
  async unfollowUser(ctx: Koa.Context) {
    ctx.body = true;
  }

  @Meta({ test: 'cc' })
  @Route.get('/meta')
  async metaTest(ctx: Koa.Context) {
    ctx.body = ctx.meta;
  }

  @Graphql
  @Middleware(middlewareLog)
  static async getUser(ctx: Koa.Context) {
    const { args } = ctx.graphql!;

    const users = [
      { username: 'skmdev', role: 'admin', userEmail: '[email protected]' },
      { username: 'foo', role: 'user', userEmail: 'bar' },
    ];

    ctx.body = users.find((user) => user.username === args.username);
  }

  @Graphql // transfrom to graphql resolver
  @Middleware(middlewareLog)
  static async getUsersGraph(ctx: Koa.Context) {
    /**
     * const { root, args, info } = ctx.graphql;
     *
     * root is representing rootObject
     *
     * args is representing the arguments of request
     *
     * info is representing the graphql info
     *
     */
    const { args } = ctx.graphql!;

    const users = [
      { username: 'skmdev', role: 'admin', userEmail: '[email protected]' },
      { username: 'foo', role: 'user', userEmail: 'bar' },
    ];

    // ctx.body is response data;
    ctx.body = users.filter((user) => user.role === args.role);
  }
}

export default UserController;




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
WeixinCloud/wxcloudrun-koa发布时间:2022-07-09
下一篇:
DCsunset/taskwarrior-webui: Responsive Web UI for Taskwarrior based on Vue.js an ...发布时间:2022-07-09
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap