|
| 1 | +import { Controller } from 'egg'; |
| 2 | + |
| 3 | +export default class UserController extends Controller { |
| 4 | + // GET /api/users?limit=5&offset=5 6~10 |
| 5 | + public async index() { |
| 6 | + const { ctx } = this; |
| 7 | + const query = { |
| 8 | + limit: parseInt(ctx.query.limit) || 10, |
| 9 | + offset: parseInt(ctx.query.offset) || 0, |
| 10 | + }; |
| 11 | + const data = await ctx.service.user.list(query); |
| 12 | + ctx.helper.rest({ |
| 13 | + ...data, // { "count": 2, "rows": [{...}, {...}] } |
| 14 | + }, 'ok', 0); |
| 15 | + } |
| 16 | + |
| 17 | + // GET /api/users/:id |
| 18 | + public async show() { |
| 19 | + const ctx = this.ctx; |
| 20 | + const data = await ctx.service.user.find(parseInt(ctx.params.id) || 0); |
| 21 | + ctx.helper.rest(data); // {...} |
| 22 | + } |
| 23 | + |
| 24 | + // POST /api/users |
| 25 | + public async create() { |
| 26 | + const { ctx } = this; |
| 27 | + // 参数校验 `ctx.request.body` 未通过将抛出 status = 422 的异常 |
| 28 | + // https://github.com/node-modules/parameter#rule |
| 29 | + const createRule = { |
| 30 | + name: 'string', |
| 31 | + age: 'int', |
| 32 | + gender: { type: 'enum', values: [ 'male', 'female', 'unknown' ], required: false }, |
| 33 | + // createdAt: { type: 'datetime', required: false }, |
| 34 | + // updatedAt: { type: 'datetime', required: false }, |
| 35 | + }; |
| 36 | + const body = ctx.request.body; |
| 37 | + ctx.validate(createRule, body); |
| 38 | + const data = await ctx.service.user.create(body); |
| 39 | + ctx.helper.rest(data); // {...} |
| 40 | + ctx.status = 201; |
| 41 | + } |
| 42 | + |
| 43 | + // PUT /api/users/:id |
| 44 | + public async update() { |
| 45 | + const { ctx } = this; |
| 46 | + const id = parseInt(ctx.params.id) || 0; |
| 47 | + const updates = { |
| 48 | + name: ctx.request.body.name, |
| 49 | + age: ctx.request.body.age, |
| 50 | + gender: ctx.request.body.gender, |
| 51 | + // updatedAt: new Date(), |
| 52 | + }; |
| 53 | + const updateRule = { |
| 54 | + name: { type: 'string', required: false }, |
| 55 | + age: { type: 'int', required: false }, |
| 56 | + gender: { type: 'enum', values: [ 'male', 'female', 'unknown' ], required: false }, |
| 57 | + }; |
| 58 | + ctx.validate(updateRule, updates); |
| 59 | + const data = await ctx.service.user.update({ id, updates }); |
| 60 | + ctx.helper.rest(data); // {...} |
| 61 | + } |
| 62 | + |
| 63 | + // DELETE /api/users/:id |
| 64 | + public async destroy() { |
| 65 | + const { ctx } = this; |
| 66 | + const id = parseInt(ctx.params.id) || 0; |
| 67 | + await ctx.service.user.del(id); |
| 68 | + ctx.helper.rest({ id }); |
| 69 | + } |
| 70 | +} |
0 commit comments