fix: template with appends (#5839)

* fix: template with appends

* fix: assign logic

* chore: test
This commit is contained in:
ChengLei Shao 2024-12-12 18:14:38 +08:00 committed by GitHub
parent 8f8f9e4af2
commit b897a8d5e6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 100 additions and 3 deletions

View File

@ -467,6 +467,8 @@ export class ACL extends EventEmitter {
}
}
const isEmptyFields = resourcerAction.params.fields && resourcerAction.params.fields.length === 0;
resourcerAction.mergeParams(parsedParams, {
appends: (x, y) => {
if (!x) {
@ -478,6 +480,11 @@ export class ACL extends EventEmitter {
return (x as any[]).filter((i) => y.includes(i.split('.').shift()));
},
});
if (isEmptyFields) {
resourcerAction.params.fields = [];
}
ctx.permission.mergedParams = lodash.cloneDeep(resourcerAction.params);
}
} catch (e) {

View File

@ -12,14 +12,14 @@ import { Collection } from '@nocobase/database';
export async function dataTemplate(ctx: Context, next) {
const { resourceName, actionName } = ctx.action;
const { isTemplate, fields } = ctx.action.params;
const { isTemplate, fields, appends } = ctx.action.params;
await next();
if (isTemplate && actionName === 'get' && fields.length > 0) {
if (isTemplate && actionName === 'get') {
ctx.body = traverseJSON(JSON.parse(JSON.stringify(ctx.body)), {
collection: ctx.db.getCollection(resourceName),
include: fields,
include: [...(fields || []), ...(appends || [])],
});
}
}

View File

@ -0,0 +1,90 @@
import { MockServer } from '@nocobase/test';
import { prepareApp } from './prepare';
describe('get action with acl', () => {
let app: MockServer;
let Post;
let Comment;
beforeEach(async () => {
app = await prepareApp();
Post = app.db.collection({
name: 'posts',
fields: [
{ type: 'string', name: 'title' },
{
type: 'bigInt',
name: 'createdById',
},
{
type: 'hasMany',
name: 'comments',
target: 'comments',
},
],
});
Comment = app.db.collection({
name: 'comments',
fields: [
{
type: 'string',
name: 'content',
},
],
});
await app.db.sync();
});
it('should get with fields', async () => {
const testRole = app.acl.define({
role: 'test',
});
testRole.grantAction('posts:view', {
fields: ['title', 'comments'],
});
testRole.grantAction('comments:view', {
fields: ['content'],
});
const [p1] = await Post.repository.create({
values: [
{
title: 'p1',
comments: [{ content: 'c1' }, { content: 'c2' }],
},
],
});
app.resourceManager.use(
(ctx, next) => {
ctx.state.currentRole = 'test';
return next();
},
{
before: 'acl',
},
);
const response = await (app as any)
.agent()
.resource('posts')
.get({
filterByTk: p1.get('id'),
fields: ['comments'],
});
expect(response.status).toBe(200);
console.log(response.body);
// expect only has comments
expect(response.body.data.title).toBeUndefined();
expect(response.body.data.comments).toBeDefined();
});
});