I'm working on a personal fullstack project (react, ts, django) using RTK Query for api calls. The models are returned by the API where relationships are denoted by their foreign key ID numbers, rather than nesting the data, for cleanliness (I'd like to keep it this way). I would like to convert these ID relationships to nested relationships on the client side from the RTK cache store using utility functions to make the necessary queries and replace IDs with their respective objects. Is there a good way to do this outside of a react component? For context:
Raw Model Interfaces:
export interface User {
id?: number;
username: string;
email: string;
first_name: string;
last_name: string;
is_superuser?: boolean;
is_staff?: boolean;
last_login?: Date;
created?: Date;
updated?: Date;
is_active?: boolean;
groups?: [];
user_permissions?: string[]
};
export interface Task {
id: number;
name: string;
creator: number;
description: string;
created: Date;
updated: Date;
assignees: number[];
committee: number;
};
export interface Committee {
id: number;
name: string;
head: number;
members: number[]
}
and the Renderable forms I want to convert them to
// User doesn't need a Renderable variant because it has no foreign key relationships
export interface CommitteeRenderable {
id: number;
name: string;
head: User;
members: User[]
}
export interface TaskRenderable {
id: number;
name: string;
creator: User;
description: string;
created: Date;
updated: Date;
assignees: User[];
committee: CommitteeRenderable
}
What I need is a way to write a function that can do something like this:
const committeeToRenderable = (committee: Committee): CommitteeRenderable => {
// These queries are the main subject of the question, performed outside of a component
const head: User = //Query the committee head user object by ID from cache
const members: User[] = //Query/filter the committee member objects by ID from cache
// Might there be some syntactic sugar to shorten this a bit?
return {
id: committee.id,
name: committee.name,
head: head,
members: members,
} as CommitteeRenderable;
}
const taskToRenderable = (task: Task): TaskRenderable => {
// These queries are the main subject of the question
const creator: User = //Query the committee creator user object by ID from cache
const assignees: User[] = //Query/filter the assigned member objects by ID from cache
const committee: Committee = //Query the committee (parent resource) by ID from cache
// Might there be some syntactic sugar to shorten this a bit?
return {
id: task.id,
name: task.name,
creator: creator,
description: task.description,
created: task.created,
updated: task.updated
assignees: assignees,
committee: committeeToRenderable(committee),
} as TaskRenderable;
}