UNPKG

dflzm

Version:

x

153 lines (144 loc) 2.49 kB
/** * @brief select user * * @param user_id * * @return {} or [] */ const selectUser = async (ctx) => { try { const { user_id } = ctx.query const attributes = ['user_id', 'user_name', 'phone', 'created_at', 'updated_at'] let rst if (user_id) { rst = await ctx.sql.user .findOne({ attributes, where: { user_id, } }) } else { rst = await ctx.sql.user .findAll({ attributes }) } ctx.body = { code: rst ? 0 : 1, msg: (user_id && !rst) || (!user_id && !rst.length) ? '没有匹配的查询结果' : '', data: rst ? rst : user_id ? {} : [], } } catch (err) { ctx.logger.error(err) ctx.body = { code: 1, msg: 'error', data: {}, } } } /** * @brief create user * * @param user_name, password, phone * * @return {} */ const createUser = async (ctx) => { try { const { user_name, password, phone, } = ctx.request.body const rst = await ctx.sql.user .create({ user_name, password, phone, }) ctx.body = { code: 0, msg: '', data: rst, } } catch (err) { ctx.logger.error(err) ctx.body = { code: 1, msg: 'error', data: {}, } } } const updateUser = async (ctx) => { try { const { user_id, user_name, password, phone, } = ctx.request.body const rst = await ctx.sql.user .update({ user_name, password, phone, }, { where: { user_id } }) ctx.body = { code: rst[0] ? 0 : 1, msg: rst[0] ? '' : '没有匹配的数据项', data: rst, } } catch (err) { ctx.logger.error(err) ctx.body = { code: 1, msg: 'error', data: {}, } } } /** * @brief delete user * * @param ctx * * @return row */ const deleteUser = async (ctx) => { try { const { user_id, } = ctx.request.body const rst = await ctx.sql.user .destroy({ where: { user_id } }) ctx.body = { code: 0, msg: '', data: rst, } } catch (err) { ctx.logger.error(err) ctx.body = { code: 1, msg: 'error', data: {}, } } } module.exports = { 'GET /user': selectUser, 'PUT /user': updateUser, 'POST /user': createUser, 'DELETE /user': deleteUser, }