4.0.3 • Published 3 years ago

koa-rest-services v4.0.3

Weekly downloads
27
License
MIT
Repository
github
Last release
3 years ago

Build Koa REST services without the hassle: quick to configure, minimal boilerplate and super convenient.

Features

  • Expose API routes with minimal config
  • Run functions before and after handling requests
  • Validate requests and provide custom error messages when keys are missing/invalid
  • Transform entities before sending them to prevent exposing sensitive data

Examples

Docs: docs

Tests: tests

Installation

yarn add koa-rest-services
// OR
npm i koa-rest-services --save

Lightweight route configuration

// app.ts

const app = new Koa()

app.use(service('/users', new UserService()))

app.listen(3000, () => console.log('Listening...'))

Clients will now have access to handler functions you implement in your service:

// UserService.ts

async get(req: ServiceRequest) {
  ...
}

async patch(req: ServiceRequest) {
  ...
}

By default you'll get a method for each HTTP method (GET/POST/PUT/PATCH/DELETE). You can also define your own routes:

// AlbumService.ts
@Routes([
  // e.g. http://example.me/albums/1/personnel/3
  {
    method: 'GET',
    path: '/:id/personnel/:personnelId',
    handler: 'getPersonnel'
  },
  // i.e. http://example.me/albums
  {
    method: 'GET',
    path: '', // can be omitted
    handler: 'getAll'
  }
])
class AlbumService implements Service {
  async getPersonnel(req: ServiceRequest) {
    ...
  }

  async getAll(req: ServiceRequest) {
    ...
  }
}

When a request is made, the specified handler function will be invoked.

Hooks

Hooks let you run functions before or after your endpoint handlers. They can modify requests/responses, validate requests and check user permissions. For example:

Validating requests:

// UserService.ts

@Validate({
  body: {
    name: 'User needs a name'
  }
})
async post(req: ServiceRequest): Promise<User> {
  user = createUser(req.body)

  return {
    status: 200,
    body: user
  }
}

Adding in metadata:

// UserService.ts

timestamp(hook: HookParams): ServiceResponse {
  // modifies the response to add a timestamp key
  const res = hook.result
  return lodash.set('res.body.timestamp', new Date())
}

@After('timestamp')
async get(req: ServiceRequest) {
  return {
    status: 200,
    body: {
      users
    }
  }
}
4.0.3

3 years ago

4.0.2

3 years ago

4.0.1

3 years ago

4.0.0

3 years ago

3.1.1

3 years ago

3.1.0

3 years ago

3.0.0

3 years ago

2.1.0

3 years ago

2.0.2

3 years ago

2.0.1

3 years ago

2.0.0

3 years ago

1.0.0

3 years ago

0.3.1

3 years ago

0.3.0

3 years ago

0.2.1

3 years ago

0.2.0

3 years ago

0.1.0

3 years ago

0.0.10

3 years ago

0.0.9

3 years ago

0.0.8

3 years ago

0.0.7

3 years ago

0.0.5

3 years ago

0.0.6

3 years ago

0.0.4

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago