As I dive into building a web application using NextJS, a versatile framework for both API and user interface implementation, I find myself pondering the best practices for modeling and handling JSON responses.
Key Points
- In my database, models are stored with foreign keys to establish relationships like many-to-many, one-to-many, and one-to-one.
- I am currently utilizing TypeScript, a programming language that supports interfaces.
- These interface declarations can be accessed from both the front end and back end of the application.
- When retrieving a model with a foreign key from the backend (API), I use an interface where the foreign key is defined as a string.
- For the frontend, rather than simply giving a reference to the object in the foreign key, I aim to include the related object directly within the JSON response.
The Challenge
To achieve this desired pattern, I find myself needing to define two similar interfaces: one for a basic shallow reference (foreign key) and another for embedding the related object.
For instance, consider a Blog Post model (Post
):
interface Post {
id: string;
creatorId: string;
}
And a User model (User
):
interface User {
id: string;
name: string;
}
To fetch data from the database, I use the Post
interface that mirrors its storage structure. However, to send nested objects to the frontend, I require a model like:
interface PostWithNested {
id: string;
creator : User;
}
resulting in a JSON structure such as:
{
"id": "X",
"creator": {
"id" : "Y",
"name": "Z";
},
}
Consider this example snippet from the API where database parsing necessitates the use of an interface:
...
const postsRepository = getRepository(Post); // contains shallow reference
const singlePost : Post = await postsRepository.findById(X);
// Embedding related object
const postWithNested : PostWithNested = {
id : singlePost.id,
user : userInstance,
}
res.status(200).json({post : postWithNested }
Is there a way to avoid declaring two almost identical interfaces that differ mainly in their treatment of related objects?