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

Added serde(skip) functionality inside Enum Variants #180

Merged
merged 2 commits into from
Dec 12, 2023

Conversation

timephy
Copy link
Contributor

@timephy timephy commented Nov 29, 2023

Observation

I wanted to skip serializing an enum error variant in a project, similar to this:

#[derive(Debug, ::thiserror::Error, serde::Serialize, ts_rs::TS)]
#[ts(export)]
#[serde(tag = "type", content = "content")]
pub enum Error {
    #[error("Account with id ({0}) not found")]
    NotFound(AccountId),
    #[error(transparent)]
    Any(
        #[from]
        #[serde(skip)]
        ::anyhow::Error,
    ),
}

This produced the following error: "skip is not applicable to newtype fields".

Problem

I wanted to skip serializing the field, to not send it to the client, as I want to keep Any errors on the server and treat them as an anonymous InternalServerError to the client.

However, I want to keep the internal error data for logging, I do not want to "delete" the error data.

It seemed like I needed a copy of my Error and omit the Any variants value (anyhow::Error), and then create a From/Into implementation from the Error with the Any field into the Error without the Any field.

Solution

In this pull request I have modified the ts-rs code so that it generates the types in the same way that serde serializes Enums in these conditions.
This is achieved by treating an Enum Variant with exactly one Unnamed field (which was already done by the code before in some places) and if that field has a skip attribute, then treat that Enum Variant as a Unit instead of a Newtype.

Tests

I implemented tests to guarantee the behaviour for all 4 types of Enum Tags (Untagged, Externally, Adjacently, Internally) both for Named and Unnamed field variants.

@NyxCode
Copy link
Collaborator

NyxCode commented Dec 12, 2023

thanks for the PR, really appreciate it!

@NyxCode
Copy link
Collaborator

NyxCode commented Dec 12, 2023

I'll merge this as-is for now, but I'll try to get rid of the repetition of if skip { .. } else { .. } before the next release.

@NyxCode NyxCode merged commit 067c3f5 into Aleph-Alpha:main Dec 12, 2023
1 check passed
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