This repository was archived by the owner on May 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Adding API resource and endpoint
Paul C edited this page Jul 18, 2018
·
2 revisions
Assuming that the resource is cats, and you want to create a GET and POST method for it.
- Define API spec in
spec/api/client/resources/cat.ts
export namespace Cats {
export const path = '/api/client/v1/cats'
export namespace GET {
export interface params {
id: number
}
export interface response {
name: string
color: string
friends: Array<Cats.GET.response>
}
}
export namespace POST {
export interface params {
name: number
color: string
}
export interface response {
id: number
}
}
}- Create server's endpoint in
server/src/route/api/client/resources/cats.ts
import ResourceRouter from '~/common/resource-router'
import { APIResponseStatus as Status } from 'spec/api/base'
import Knex from '~/db/connection'
import { Context } from '~/route/interfaces'
import { Cats } from 'spec/api/client/resources/cats'
const router = new ResourceRouter()
/**
* /api/v1/cats
*
*/
router.get(
Cats.path,
async (ctx: Context<Cats.GET.params, Cats.GET.response>) => {
const { id } = ctx.request.body
const cat = await Knex('cats')
.where({ id })
.first()
ctx.success(Status.OK, { cat })
}
)
router.post(
Cats.path,
async (ctx: Context<Cats.POST.params, Cats.POST.response>) => {
const { name, color } = ctx.request.body
const id = await Knex('cats').insert({ name, color })
ctx.success(Status.OK, { id })
}
)
export default router