data icon indicating copy to clipboard operation
data copied to clipboard

Nullable object properties

Open roertbb opened this issue 3 years ago • 0 comments

Hi there! 👋 I stumbled upon that case 2 or 3 times and decide to give it a shot to solve my problem and most likely help some other great folks as well 😄

I've read the hints from https://github.com/mswjs/data/discussions/202, extended ModelValueType, adjusted the generation of nested object values within nullable nested objects and also adjusted types here and there to properly handle nullable nested objects.

Sharing some context behind technical decisions/changes I've made:

  • I decided to add isGetterFunctionReturningObject to NullableProperty - it indicates if we should generate properties for nested nullable objects in src/model/parseModelDefinition.ts. It's needed when we have some getter function returning object with nested properties in factory and we're not providing any value for these nested object properties during model creation (case is covered in nullable object property > when object getter is provided in factory definition > defaults to value provided in factory when not set during model creation test)
  • I also created getDefinition function to "unwrap" the getter value from NullableProperty when we want to get the default values of nested properties within nullable object properties
  • I've extended the type for Value in glossary.ts to properly infer types in case of some object is passed as generic type. It was also needed to make nulllable<Date>(() => null) to work properly (you can find some examples in test/query/date.test.ts)
  • changes in src/query/queryTypes.ts were required when querying dates with lte / gte (case is covered in ignores entities with missing values when querying using date test)

I tried to provide API without a getter function (as mentioned in https://github.com/mswjs/data/issues/203), however I failed on providing proper typing for it (some raw PoC can be found in https://github.com/roertbb/data/pull/1). Recently, decided to neglect that idea and try out extending existing NullableProperty (which is using getter function) to incorporate objects there.

Working on that one was a pretty good journey into depths of mswjs/data, I think I understood quite some of them, but I still may be missing some other parts - I'd be really grateful for guidance on what I could've missed or how I could make it more elegant and readable 😉

I also wrote couple of tests that served me as a test cases. These are not extensively testing all the possible use-cases, but should be a good foundation. If you have other test-cases on your mind, if you feel that it will be more readable to structure tests some other way - please share some feedback 😉

Resolves #203

roertbb avatar Jul 03 '22 12:07 roertbb