cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

sap build code authorization error: Cannot read properties of undefined (reading '$count')

mostafa4
Explorer
0 Kudos
500

I am working on a CAP (Cloud Application Programming) model where I have an entity called booksService.books, and I am applying role-based access control to filter certain fields based on user roles.

entity books {
key ID : UUID;
title : String;
author : String;
Sales : Integer;
Price : Integer;

User Roles and Their Permissions:

  • AdminAll → Can see all data
  • viewExSales → Can see all fields except sales 

I initially wrote this event handler to modify the query when a user has the "viewExSales" role, so they cannot see the Sales column:

 

/**
 * 
 * @On(event = { "READ" }, entity = "booksService.books")
 * @Param {Object} request - User information, tenant-specific CDS model, headers, and query parameters
 */
module.exports = async function (request) {
    if (request.user.is('viewExSales')) {
        // Remove the 'Sales' column from the query
        request.query.columns = request.query.columns.filter(column => column !== 'Sales');
    }
};

 

 i get error

 

[cds] - ️Uncaught TypeError: Cannot read properties of undefined (reading '$count')
    at all (/home/user/projects/books/node_modules/@sap/cds/libx/_runtime/fiori/lean-draft.js:982:80)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async cds.ApplicationService.handle (/home/user/projects/books/node_modules/@sap/cds/libx/_runtime/fiori/lean-draft.js:447:20)

 

So, I also tried implementing manual query filtering based on roles like this

 

module.exports = async function(request) {
    const { books } = cds.entities;
    const user = request.user;
    
    let columns = ['ID', 'title', 'author', 'Sales', 'Price'];

    if (user) {
        const userRoles = Array.isArray(user.roles) ? user.roles : Object.keys(user.roles);

        if (userRoles.includes('AdminAll')) {
            return await SELECT.from(books).columns(...columns);
        } 
        
        if (userRoles.includes('viewExSales')) {
            columns = columns.filter(col => col !== 'Sales');
        }

        return await SELECT.from(books).columns(...columns);
    } 

    return await SELECT.from(books).columns(...columns);
};

 

it works and returned the data correctly but there were issues in it

Issue:

  1. Filters and searches applied via the generated Fiori UI are ignored.
  • If I filter by title or author, the backend still returns the full dataset instead of the filtered results.
  • It seems like my custom query is overriding the default behavior of CAP filtering.

Accepted Solutions (0)

Answers (0)