Files
certd/packages/libs/lib-server/src/basic/base-controller.ts
2024-12-23 00:24:31 +08:00

51 lines
939 B
TypeScript

import { Inject } from '@midwayjs/core';
import * as koa from '@midwayjs/koa';
import { Constants } from './constants.js';
export abstract class BaseController {
@Inject()
ctx: koa.Context;
/**
* 成功返回
* @param data 返回数据
*/
ok(data?: any) {
const res = {
...Constants.res.success,
data: undefined,
};
if (data) {
res.data = data;
}
return res;
}
/**
* 失败返回
* @param msg
* @param code
*/
fail(msg: string, code?: any) {
return {
code: code ? code : Constants.res.error.code,
msg: msg ? msg : Constants.res.error.code,
};
}
getUserId() {
const userId = this.ctx.user?.id;
if (userId == null) {
throw new Error('Token已过期');
}
return userId;
}
getLoginUser() {
const user = this.ctx.user;
if (user == null) {
throw new Error('Token已过期');
}
return user;
}
}