item.js 2.49 KB
Newer Older
wuhao's avatar
wuhao committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
'use strict';

const Controller = require('../core/base_controller');

function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class ItemController extends Controller {
  async mutisort() {
    const ctx = this.ctx;
    const updates = await ctx.service.item.mutiupdate(
      ctx.request.body?.sortlist ?? []
    );
    this.success(updates);
  }

  async index() {
    const ctx = this.ctx;
    const query = {
      limit: toInt(ctx.query.limit),
      offset: toInt(ctx.query.offset),
    };
    const result = await ctx.model.Item.findAll(query);
    this.success(result);
  }

  async show() {
    const ctx = this.ctx;
    const result = await ctx.model.Item.findByPk(toInt(ctx.params.id));
    this.success(result);
  }

  async create() {
    const ctx = this.ctx;
    console.log(ctx.request.body);
    if (!ctx.request.body.mission_name || !ctx.request.body.project_id) {
      this.fail('请完善必填项!');
      return;
    }
wuhao's avatar
wuhao committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    const tags = ctx.request.body.tags
      ?.filter(it => isNaN(it))
      .map(it => {
        return {
          tag_name: it,
          project_id: ctx.request.body.project_id,
          color: '#cccccc',
        };
      });
    const idtags = await ctx.model.Tag.findAll({
      where: {
        id: ctx.request.body.tags?.filter(it => !isNaN(it)),
      },
    });
    const mutiadder = await ctx.service.tag.muticreate(tags);
    const tages = [
      mutiadder?.map(it => it?.dataValues),
      idtags.map(it => it?.dataValues),
    ].flat();
    const item = await ctx.model.Item.create({
      ...ctx.request.body,
      tags: tages,
    });
wuhao's avatar
wuhao committed
66
    // const tags = await ctx.model.service.tags
wuhao's avatar
wuhao committed
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    this.success(item);
  }

  async update() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const item = await ctx.model.Item.findByPk(id);
    if (!item) {
      ctx.status = 404;
      ctx.body = {
        code: 1,
        success: false,
        msg: '库里没有该条数据',
      };
      return;
    }
    await item.update(ctx.request.body);
    this.success(item);
  }

  async destroy() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const item = await ctx.model.Item.findByPk(id);
    if (!item) {
      ctx.status = 404;
      ctx.body = {
        code: 1,
        success: false,
        msg: '库里没有该条数据',
      };
      return;
    }

    await item.destroy();
    this.success({
      data: '已删除',
    });
  }
}

module.exports = ItemController;