Description
Is your feature request related to a problem? Please describe.
When writing integration tests for our project, we need to deserialize the response from requests into the actual classes from the project. This allows us to verify if the program returned the correct data by comparing the returned instance with an expected one. Currently, we're using a workaround to parse the results, but this has its limitations, specifically when it comes to relationships.
Describe the solution you'd like
We're looking for a more robust solution for parsing the response from a request in our integration tests. Ideally, this solution should be able to handle relationships and other complexities in the response. It would be great if there were a built-in method or feature in JsonApiDotNetCore that could facilitate this.
Describe alternatives you've considered
Currently, we're using a custom JsonApiDocumentParser class to parse the response. This class uses the IResourceObjectAdapter and IJsonApiOptions services to convert the response data into our project's classes. However, this solution is not ideal as it feels like a "hack" and has limitations. We also tried other client libraries such as JsonApiFramework.Client
, but this resulted in a lot of setup.
Additional context
Here's our current solution:
public class JsonApiDocumentParser : IDisposable
{
...
public JsonApiDocumentParser(WebApplicationFactory<Program> factory)
{
_scope = factory.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
_adapter = _scope.ServiceProvider.GetRequiredService<IResourceObjectAdapter>();
_options = _scope.ServiceProvider
.GetRequiredService<IJsonApiOptions>()
.SerializerReadOptions;
}
public async Task<(Document, object?)> Parse(HttpContent content)
{
string contentAsString = await content.ReadAsStringAsync();
Document document = JsonSerializer.Deserialize<Document>(contentAsString, _options)!;
SingleOrManyData<ResourceObject> data = document.Data;
if (!data.IsAssigned || data.Value == null)
return (document, null);
object convertedData =
data.SingleValue != null
? ConvertedData(data.SingleValue)
: data.ManyValue!.Select(ConvertedData).ToList();
return (document, convertedData);
}
private IIdentifiable ConvertedData(ResourceObject data)
{
RequestAdapterState state =
new(new JsonApiRequest(), new TargetedFields())
{
WritableTargetedFields = new TargetedFields()
};
return _adapter.Convert(data, new ResourceIdentityRequirements(), state).resource;
}
}