When developing a web app's back-end with TypeScript, I've found intersection types to be incredibly beneficial for optimizing SQL queries. Imagine having the following tables:
User
userId: number
userEmail: string
Post
postId: number
userId: number (FK)
postBody: string
By combining these two tables into an intersection type (User & Post), we get:
{
userId: number;
userEmail: string;
postId: number;
postBody: string;
}
This allows us to represent rows returned from a joined select query using this type.
The challenge arises when we need to deconstruct this data on the web server. Writing iterative code to group results for every query can become repetitive. The desired transformation is as follows:
Input:
[
{
userId: 1,
userEmail: 'user1@example.com',
postId: 1,
postBody: 'User 1\'s first post',
},
{
userId: 1,
userEmail: 'user1@example.com',
postId: 2,
postBody: 'User 1\'s second post',
},
{
userId: 2,
userEmail: 'user2@example.com',
postId: 3,
postBody: 'User 2\'s first post',
},
]
Output:
[
{
userId: 1,
userEmail: 'user1@example.com',
posts: [
{
postId: 1,
postBody: 'User 1\'s first post',
},
{
postId: 2,
postBody: 'User 1\'s second post',
}
],
},
{
userId: 2,
userEmail: 'user2@example.com',
posts: [
{
postId: 3,
postBody: 'User 2\'s first post',
}
]
}
]
I'm looking to create a dynamic function for achieving this, by passing in the collection, an array of parent key names, and the name of the child collection. My attempt at implementing this function resulted in:
function group(coll: Array<any>, parentKeys: Array<string>, childCollName: string): Array<any>;
If anyone has suggestions or can assist with the implementation, it would be greatly appreciated.
So far, efforts have been made with Lodash but the groupBy
function doesn't handle subobjects equally, leading to unexpected results such as an array of three objects instead of a nested structure.