|
1 | 1 | import { Controller } from 'egg'; |
2 | 2 |
|
3 | | -// 定义创建接口的请求参数规则 |
4 | | -// https://github.com/node-modules/parameter#rule |
5 | | -const createRule = { |
6 | | - name: 'string', |
7 | | - type: { type: 'enum', values: [ 'ask', 'share' ], required: false }, |
8 | | -}; |
9 | | - |
10 | 3 | export default class DemoController extends Controller { |
11 | | - // GET /demo |
| 4 | + |
| 5 | + // GET / |
12 | 6 | public async index() { |
13 | 7 | const { ctx } = this; |
14 | | - ctx.logger.debug('test logger'); |
| 8 | + ctx.response.redirect('/public/test.html'); |
| 9 | + } |
| 10 | + |
| 11 | + // GET /api/demo |
| 12 | + public async testEnv() { |
| 13 | + const { ctx } = this; |
15 | 14 | ctx.body = `<h1>${ctx.app.env}</h1>`; // local |
16 | 15 | ctx.response.type = 'text/html'; |
17 | 16 | ctx.status = 200; |
18 | | - |
19 | | - // ctx.app.redis.get() |
20 | | - // client.on('connect', function () { |
21 | | - // // set 语法 |
22 | | - // client.set('lubanH5makerTest', 'csxiaoyao', function (err, data) { |
23 | | - // console.log(1, data) |
24 | | - // }) |
25 | | - // // get 语法 |
26 | | - // client.get('lubanH5makerTest', function (err, data) { |
27 | | - // console.log(2, data) |
28 | | - // }) |
29 | | - // }) |
30 | 17 | } |
31 | 18 |
|
32 | | - // GET /demo/new |
33 | | - public async new() { |
| 19 | + // GET /api/demo/:id |
| 20 | + public async testThrowError() { |
34 | 21 | const { app, ctx } = this; |
| 22 | + ctx.logger.debug('testThrowError with id: %j', ctx.params.id); |
35 | 23 | ctx.throw({ |
36 | 24 | code: app.config.CODE.TEST_ERROR, |
37 | 25 | message: '测试错误抛出', |
38 | 26 | }); |
39 | 27 | } |
40 | 28 |
|
41 | | - // POST /demo |
42 | | - public async create() { |
43 | | - const { ctx } = this; |
44 | | - // 校验 `ctx.request.body` 是否符合我们预期的格式 |
45 | | - // 如果参数校验未通过,将会抛出一个 status = 422 的异常 |
46 | | - ctx.validate(createRule, ctx.request.body); |
47 | | - // 调用 service 创建一个 demo |
48 | | - const data = await ctx.service.demo.create(ctx.request.body); |
49 | | - // 设置响应体和状态码 |
50 | | - ctx.helper.rest({ |
51 | | - ...data, |
52 | | - }, 'ok', 0); |
53 | | - } |
54 | | - // GET /demo/:id |
55 | | - public async show() { |
56 | | - const { ctx } = this; |
57 | | - ctx.logger.debug('fetch id: %j', ctx.params.id); |
58 | | - console.log('test show'); |
59 | | - } |
60 | | - // GET /demo/:id/edit edit_demo |
61 | | - public async edit() { |
62 | | - console.log('test edit'); |
63 | | - } |
64 | | - // PUT /demo/:id demo |
65 | | - public async update() { |
66 | | - console.log('test update'); |
67 | | - } |
68 | | - // DELETE /demo/:id demo |
69 | | - public async destroy() { |
70 | | - console.log('test destroy'); |
| 29 | + // POST /api/demo |
| 30 | + public async testRedis() { |
| 31 | + const { app, ctx } = this; |
| 32 | + await app.redis.set('test', ctx.request.body.test); |
| 33 | + const data = await app.redis.get('test'); |
| 34 | + ctx.helper.rest(data); |
71 | 35 | } |
72 | 36 | } |
0 commit comments