Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a source generator to generate versioned DTOs #1466

Merged
merged 2 commits into from
Aug 19, 2024
Merged

Conversation

gunndabad
Copy link
Collaborator

@gunndabad gunndabad commented Aug 16, 2024

In working on a new version of an API endpoint I've run into issues with API model duplication. Amending a type in the new version that's re-used across multiple endpoints requires redefining every controller action, request, response and API model type that is in the dependency graph to keep schema generation happy - this is too much pain.

This PR resurrects and tidies up an old source generation POC I did some time ago. With it you can annotate a type with [GenerateVersionedDto(<some type>)] and a partial declaration will be generated with all the members of the referenced type. Other referenced types will be generated recursively. This means you can have a stub type like:

[GenerateVersionedDto(typeof(SomeOldVersion.Responses.GetPersonResponse))]
public partial record GetPersonResponse;

and all the members from SomeOldVersion.Responses.GetPersonResponse will be cloned onto another partial record GetPersonResponse along with all the types that SomeOldVersion.Responses.GetPersonResponse references. This makes it significantly easier to add new API versions that tweak existing response schema.

In future I'd like to amend the source generator to be an incremental source generator but in the interests of time I've not done that here.

The first commit here is the source generator itself and the second makes the necessary changes to use it. I've also removed some re-use of request/response types across versions; each endpoint should use request and response types from its version only.

@gunndabad gunndabad marked this pull request as ready for review August 16, 2024 12:36
@MrKevJoy MrKevJoy self-requested a review August 16, 2024 12:46
@gunndabad gunndabad merged commit ced2453 into main Aug 19, 2024
13 checks passed
@gunndabad gunndabad deleted the dto-source-gen branch August 19, 2024 06:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants