'use strict'; const qs = require('qs'); const Controller = require('egg').Controller; const uuid = require('node-uuid'); class UserController extends Controller { async info() { const ctx = this.ctx; const id = ctx.params.id; try { const result = await ctx.service.user.find(id); this.ctx.body = { result, success: true, }; } catch (error) { this.ctx.body = { success: false, error, }; } } async list() { const param = qs.parse(this.ctx.query); const ctx = this.ctx; try { const result = await ctx.service.user.list(param); const total = await ctx.service.user.count(); this.ctx.body = { result, total: total[0].total, success: true, }; } catch (error) { this.ctx.body = { success: false, error, }; } } async add() { const ctx = this.ctx; const id = uuid.v4(); const data = ctx.request.body; data.id = id; try { await ctx.service.user.add(data); this.ctx.body = { success: true }; } catch (error) { this.ctx.body = { success: false, error }; } } async update() { const ctx = this.ctx; const data = ctx.request.body; try { await ctx.service.user.update(data); this.ctx.body = { success: true }; } catch (error) { this.ctx.body = { success: false, error }; } } async password() { const ctx = this.ctx; const data = ctx.request.body; try { const result = await ctx.service.user.password(data); const { affectedRows = 0 } = !result ? {} : result; if (affectedRows > 0) { this.ctx.body = { success: true }; } else { this.ctx.body = { success: false, error: '原密码错误' }; } } catch (error) { this.ctx.body = { success: false, error }; } } async remove() { const ctx = this.ctx; try { await ctx.service.user.remove(ctx.request.body); this.ctx.body = { success: true }; } catch (error) { this.ctx.body = { success: false, error }; } } async login() { const ctx = this.ctx; const data = ctx.request.body; try { const results = await ctx.service.user.login(data); if (results.length > 0) { const userInfo = results[0]; this.ctx.body = { result: userInfo, success: true }; } else { this.ctx.body = { success: false, error: '用户名或密码不正确' }; } } catch (error) { this.ctx.body = { success: false, error }; } } async validate() { const ctx = this.ctx; const data = ctx.request.body; try { const results = await ctx.service.user.validate(data); if (results.length > 0) { this.ctx.body = { success: true }; } else { this.ctx.body = { success: false, error: '用户密码不正确' }; } } catch (error) { this.ctx.body = { success: false, error }; } } } module.exports = UserController;