使用ai辅助生成koa后端接口

nodejs yekong

最近做数据可视化大屏项目过程中,客户需要后端功能,于是想着可不可以通过ai辅助我来实现后端api接口的开发呢?

今天我们来实现一个分类接口的增删改查功能的实现

ai辅助生成代码

描述越详细生成的代码也越符合我们的需要比如生成一个党员管理的增删改查接口

lin-cms-koa 党员管理 
字段如下
姓名 性别 出生日期 学历 职务 入党日期 政治面貌 所在党组织 所在单位 

请生成api接口和相关代码 请按照下面网页里的内容生成我想要的代码 https://www.wanjunshijie.com/note/nodejs/10752.html

api端

接口的增删改查四个接口

import { LinRouter, NotFound } from "lin-mizar";
import { PartyCategory } from "../../model/party-category";
import { PositiveIdValidator } from "../../validator/common";
import { CategoryValidator } from "../../validator/party-category";

const partyCategoryApi = new LinRouter({
    prefix: "/v1/party-category"
});

const responseWrapper = (ctx, data, msg = '操作成功') => {
    ctx.body = {
        code: 1,
        data,
        msg
    };
};

const errorHandler = (ctx, error) => {
    console.error(error);
    ctx.body = {
        code: 0,
        data: null,
        msg: error.message || '操作失败'
    };
};

partyCategoryApi.get("/", async (ctx) => {
    try {
        const categories = await PartyCategory.findAll();
        responseWrapper(ctx, categories, '获取党组织分类列表成功');
    } catch (error) {
        errorHandler(ctx, error);
    }
});

partyCategoryApi.post("/", async (ctx) => {
    try {
        const v = await new CategoryValidator().validate(ctx);
        const category = await PartyCategory.create({
            name: v.get('body.name'),
            value: v.get('body.value')
        });
        responseWrapper(ctx, category, '创建党组织分类成功');
    } catch (error) {
        errorHandler(ctx, error);
    }
});

partyCategoryApi.put("/:id", async (ctx) => {
    try {
        const v = await new CategoryValidator().validate(ctx);
        const id = v.get('path.id');
        const category = await PartyCategory.findByPk(id);
        if (!category) {
            throw new NotFound({
                code: 10022
            });
        }
        category.name = v.get('body.name');
        category.value = v.get('body.value');
        await category.save();
        responseWrapper(ctx, category, '更新党组织分类成功');
    } catch (error) {
        errorHandler(ctx, error);
    }
});

partyCategoryApi.delete("/:id", async (ctx) => {
    try {
        const v = await new PositiveIdValidator().validate(ctx);
        const id = v.get('path.id');
        const category = await PartyCategory.findByPk(id);
        if (!category) {
            throw new NotFound({
                code: 10022
            });
        }
        await category.destroy();
        responseWrapper(ctx, null, '删除党组织分类成功');
    } catch (error) {
        errorHandler(ctx, error);
    }
});

export { partyCategoryApi };

model端

也就是数据库的字段

import { Model, Sequelize } from 'sequelize'
import sequelize from '../lib/db'

class PartyCategory extends Model {}

PartyCategory.init({
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    name: {
        type: Sequelize.STRING(50),
        allowNull: false,
        comment: '分类名称'
    },
    value: {
        type: Sequelize.INTEGER,
        allowNull: false,
        defaultValue: 0,
        comment: '数量'
    }
}, {
    sequelize,
    tableName: 'party_category'
})

export { PartyCategory }

validator验证

接口字段的验证

import { LinValidator, Rule } from 'lin-mizar'

class CategoryValidator extends LinValidator {
    constructor() {
        super()
        this.name = [
            new Rule('isLength', '名称长度必须在1~50之间', {
                min: 1,
                max: 50
            })
        ]
        this.value = [
            new Rule('isInt', '数量必须是正整数', { min: 0 })
        ]
    }
}

export { CategoryValidator }

dao

如果接口功能稍微复杂点的话,可能还需要dao,比如分页查询

import { Op } from 'sequelize';
import { PartyMember } from "../model/partyMember";
import { Category } from "../model/category";

class PartyMemberDao {
    async getPartyMembers(page, pageSize, name = '') {
        const offset = (page - 1) * pageSize;
        const where = {};

        if (name) {
            where.name = {
                [Op.like]: `%${name}%`
            };
        }

        const { count, rows } = await PartyMember.findAndCountAll({
            where,
            offset,
            limit: pageSize,
            order: [['id', 'ASC']],
            include: [{ model: Category, as: 'category' }]
        });
        return {
            items: rows,
            total: count
        };
    }

    async getPartyMember(id) {
        const partyMember = await PartyMember.findByPk(id, {
            include: [{ model: Category, as: 'category' }]
        });
        return partyMember;
    }

    async createPartyMember(v) {
        const partyMember = await PartyMember.createPartyMember(v);
        return partyMember;
    }

    async updatePartyMember(id, v) {
        const partyMember = await PartyMember.updatePartyMember(id, v);
        return partyMember;
    }

    async deletePartyMember(id) {
        await PartyMember.deletePartyMember(id);
    }
}

export { PartyMemberDao };

喜欢