Determine whether a many-to-many relationship involves a specific entity

I am currently working on developing an API for managing surveys. One challenge I'm facing is determining whether a specific user has moderation privileges for a particular survey. A many-to-many relationship has been set up between the two entities.

The process goes like this: A user sends a request to the server, which is authenticated by a token providing the user's id and email address. The request is then routed using the survey id as input. The actual user and survey data are retrieved from the database and stored in separate variables. What remains is figuring out if the user is listed as a moderator for the survey.

Additional note based on some comments: The main question is how can I achieve this? As the "user.moderates" (relation name on the user side) and "survey.moderators" (inverse relation) properties are not included in the database Entities retrieval.

In essence, I need a way to retrieve all moderators of a survey and verify if the given user is among them

Snippet of code in the request:

user = await getUser(res.locals.keycloakId);
if (user === null)
{
    res.status(404).json({error: "User does not exist"});
}
else
{
    survey = getSurveyById(+req.params['id'];
    if (survey === null)
    {
        res.status(404).json({error: "Survey does not exist"});
    }
    else
    {
        if (!await hasAccess(user, survey))
        {
            res.status(403).json({error: "User is not allowed to access this survey"});
        }
    }
}

The task now lies in the hasAccess function, which determines whether the user should have access to the survey. Here’s what it looks like at the moment:

export async function hasAccess(user: User, survey: Survey): Promise<boolean>
{
    if (// implement check for user's access to survey)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Answer №1

While it may not be the most elegant approach, I was able to come up with a solution. By sending another request for the survey and filtering for relationships this time, you can simply check if the result is null.

You can use code similar to this:

async function hasAccess(user, survey) {
    let relationships = await Survey.findOne({
        moderators: user,
        id: survey.id,
    });
    return relationships !== null;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Cannot display data in template

After successfully retrieving JSON data, I am facing trouble displaying the value in my template. It seems that something went wrong with the way I am trying to output it compared to others. My function looks like this, getUserInfo() { var service ...

Specifying the return type of a function as a combination of the types of the input arguments

Is there a way to safely implement the given function in TypeScript without using unsafe casts or an extensive number of function overloads with various input permutations? interface Wrapped<T> { type: string; data: T; } interface WrappedA&l ...

Injection of dependencies in Angular can be done outside of the constructor

In my class, I have a constructor that takes in some data. export class MyClass { constructor(data: any) { this.data = data; } } I also want to include ChangeDetectorRef as a parameter in the constructor like this. constructor(data: any, cd: ...

Learn how to create a versatile TypeScript function that combines an array parameter and values to form an object

I've created a function that combines an array of keys with an array of values to form an object. Here's how the function looks: function mergeToObject(keys: string[], values: string[]) { const object:? = {} for (let i = 0; i < keys.length ...

A software piece producing a JSX element that generates a single function

Is it possible to create a JSX element or component that returns a single function as its child? For instance: interface ComponentChildrenProps { someProp: string; } const Component: React.FC<ComponentProps> = ({ children }): JSX.Element => { ...

What is the most effective method for declaring callbacks on objects in Typescript?

I am currently working on a sidebar menu component that is connected to a service holding items in the menu. This allows multiple sources to make alterations to the menu as needed. Each item in the menu currently follows the SidebarItem interface: export ...

Enhance React component props for a styled component element using TypeScript

Looking to enhance the properties of a React component in TypeScript to include standard HTML button attributes along with specific React features such as ref. My research suggests that React.HTMLProps is the ideal type for this purpose (since React.HTMLA ...

Record the success or failure of a Protractor test case to generate customized reports

Recently, I implemented Protractor testing for our Angular apps at the company and I've been searching for a straightforward method to record the pass/fail status of each scenario in the spec classes. Is there a simple solution for this? Despite my at ...

Exploring the process of dynamically updating a form based on user-selected options

I need assistance with loading an array of saved templates to be used as options in an ion-select. When an option is chosen, the form should automatically update based on the selected template. Below is the structure of my templates: export interface ...

Identifying the End of an HTML Video in Angular 2

Seeking assistance with detecting the end of an HTML video in Ionic2 (Angular2 and Typescript). The relevant code snippets can be found below: Template: <video poster="" id="v" playsinline autoplay webkit-playsinline onended="vidEnded()"> <s ...

how to use all parameters except the first one in TypeScript

Is there a way to reference one function's parameter types in another function, but only use a subset of them without repeating the entire list of parameters? //params of bar should be same as foo, except p1 should be a different type function foo(p1 ...

What is the official name of the key type for the Built-in Object?

There was a built-in type that I used in the past which represented the union of all possible object keys. It was named objectKey or something similar. Here is an example: type objectKey = string | number | symbol Unfortunately, I am drawing a blank on t ...

The .ts source file is mysteriously missing from the development tool's view after being deployed

When I work locally, I can see the .ts source files, but once I deploy them, they are not visible in any environment. Despite setting my sourcemap to true and configuring browserTargets for serve, it still doesn't work. Can someone help with this issu ...

What could be causing the Toast message to not show up in react-native-root-toast?

Incorporated react-native-root-toast into my expo project running on expo 51. Please see the code snippet below for reference: const toastColors = { 'error': { color: '#DA5C53', iconName: <WarningIcon size="5 ...

Building a filter for a union type in TypeScript: a step-by-step guide

Allow me to present an example to demonstrate my current objective. const v1: { type: "S"; payload: string } = { type: "S", payload: "test" }; const v2: { type: "N"; payload: number } = { type: "N", payload: 123 }; type Actions = typeof v1 | typeof v2; ...

Adding elements from one array to another array of a different type while also including an additional element (JavaScript/TypeScript)

I'm having trouble manipulating arrays of different types, specifically when working with interfaces. It's a simple issue, but I could use some help. Here are the two interfaces I'm using: export interface Group { gId: number; gName: st ...

Tips for maintaining the active state of an item within a component that loops through a dataset

I am working with an array of objects (specifically, posts represented as strings) and I am looking to be able to edit each one individually. However, I am encountering an issue where clicking on the edit button triggers editing for all posts at once: co ...

Is the client component not initializing the fetch operation?

On my page, there is a sidebar that displays items by fetching data successfully. However, when I click on one of the sidebar items to pass props to another component for fetching data, it doesn't fetch any data until I manually click the refresh butt ...

Error message: "Angular requires either importing or local installation"

For my ionic application development, I encountered an issue while trying to link pages together in the ionic creator. The error message on the .ts file is: typescript: src/pages/home/home.ts, line: 4 Individual declarations in merged declar ...

Encountering an error when attempting to show user details on a webpage using Angular and Ionic with Promise functionality

On my app's AccountSettingsPage, I am fetching user data from a SQLite DB and displaying it on an Ionic page. However, I encountered the following error: Error: TypeError: Cannot read property 'name' of undefined at Object.eval [as upd ...