lincms如何进行权限控制

nodejs yekong

权限控制我们通过下面的方法来实现权限控制。

policeRatioApi.permission('接警占比新增'),
groupRequired,

接口完整实例

// 文件:api/v1/policeRatio.js

import {LinRouter, NotFound, ParametersException} from 'lin-mizar';
import {groupRequired} from '../../middleware/jwt';
import {PositiveIdValidator} from '../../validator/common';
import {CreateOrUpdatePoliceRatioValidator} from '../../validator/policeRatio';
import {PoliceRatioDao} from '../../dao/policeRatio';
import {PoliceRatio} from '../../model/policeRatio';
import * as XLSX from 'xlsx';
import fs from 'fs';

const policeRatioApi = new LinRouter({
    prefix: '/v1/police-ratio',
    module: '接警占比'
});

const policeRatioDao = new PoliceRatioDao();

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 || '操作失败'
    };
};

// 获取接警占比列表
policeRatioApi.get('/', async (ctx) => {
    try {
        const page = parseInt(ctx.query.page) || 1;
        const pageSize = parseInt(ctx.query.pageSize) || 10;
        const {items, total} = await policeRatioDao.getPoliceRatioData(page, pageSize);
        responseWrapper(ctx, {list: items, total, page, pageSize}, '获取接警占比数据列表成功');
    } catch (error) {
        errorHandler(ctx, error);
    }
});

// 创建接警占比
policeRatioApi.linPost(
    'createPoliceRatio',
    '/',
    policeRatioApi.permission('接警占比新增'),
    groupRequired,
    async (ctx) => {
        try {
            const v = await new CreateOrUpdatePoliceRatioValidator().validate(ctx);
            console.log('Validated data:', v);
            const policeRatio = await policeRatioDao.createPoliceRatio(v.get('body'));
            responseWrapper(ctx, policeRatio, '创建接警占比成功');
        } catch (error) {
            console.error('Error in create police ratio:', error);
            errorHandler(ctx, error);
        }
    }
);

// 更新接警占比
policeRatioApi.linPut(
    'updatePoliceRatio',
    '/:id',
    policeRatioApi.permission('接警占比修改'),
    groupRequired,
    async (ctx) => {
        const v = await new CreateOrUpdatePoliceRatioValidator().validate(ctx);
        const id = parseInt(ctx.params.id);
        try {
            const policeRatio = await policeRatioDao.updatePoliceRatio(id, v.get('body'));
            responseWrapper(ctx, policeRatio, '更新接警占比成功');
        } catch (error) {
            errorHandler(ctx, error);
        }
    }
);

// 删除接警占比
policeRatioApi.linDelete(
    'deletePoliceRatio',
    '/:id',
    policeRatioApi.permission('接警占比删除'),
    groupRequired,
    async (ctx) => {
        const id = parseInt(ctx.params.id);
        try {
            await policeRatioDao.deletePoliceRatio(id);
            responseWrapper(ctx, null, '删除接警占比成功');
        } catch (error) {
            errorHandler(ctx, error);
        }
    }
);

// 导出接警占比数据
policeRatioApi.get("/export", async (ctx) => {
    try {
        const buffer = await PoliceRatio.exportPoliceRatioData();
        ctx.set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        const filename = encodeURIComponent('接警占比数据.xlsx');
        ctx.set('Content-Disposition', `attachment; filename*=UTF-8''${filename}`);
        ctx.body = buffer;
    } catch (error) {
        errorHandler(ctx, error);
    }
});

// 导入接警占比数据
policeRatioApi.linPost(
    'importPoliceRatio',
    "/import",
    policeRatioApi.permission('接警占比导入'),
    groupRequired,
    async (ctx) => {
        const file = ctx.request.files.file;

        if (!file) {
            throw new NotFound({code: 10024, message: '没有上传文件'});
        }

        try {
            if (!file.filepath || !fs.existsSync(file.filepath)) {
                throw new Error('文件不存在或路径无效');
            }

            const fileContent = fs.readFileSync(file.filepath);
            if (!fileContent || fileContent.length === 0) {
                throw new Error('文件内容为空');
            }

            let workbook;
            try {
                workbook = XLSX.read(fileContent, {type: 'buffer'});
            } catch (readError) {
                throw new Error(`Excel文件读取失败: ${readError.message}`);
            }

            if (!workbook.SheetNames.length) {
                throw new Error('Excel文件没有工作表');
            }

            const sheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[sheetName];

            if (!worksheet) {
                throw new Error('无法获取工作表内容');
            }

            const rawData = XLSX.utils.sheet_to_json(worksheet);

            if (!rawData || rawData.length === 0) {
                throw new Error('Excel文件内容为空');
            }

            const importResult = await PoliceRatio.importPoliceRatioData(rawData);

            const isFullySuccessful = importResult.successCount === rawData.length;

            responseWrapper(ctx, {
                totalRows: rawData.length,
                successCount: importResult.successCount,
                failureCount: importResult.failureCount,
                failures: importResult.failures
            }, isFullySuccessful
                ? `文件解析并导入成功,成功导入 ${importResult.successCount} 条记录`
                : `文件部分导入成功,成功导入 ``{importResult.successCount} 条记录,失败 ``{importResult.failureCount} 条记录`);
        } catch (error) {
            errorHandler(ctx, error);
        }
    }
);

export {policeRatioApi}

查询权限

我们就可以通过接口获取到我们配置的权限了。

查询权限

喜欢