dynamodb-toolbox icon indicating copy to clipboard operation
dynamodb-toolbox copied to clipboard

Derived state

Open codingnuclei opened this issue 1 year ago • 6 comments

Hi,

Is it possible to have an entity with derived state?

i.e. if an item in a table has the attributes: oneStar twoStar threeStar fourStar fiveStar. When i do a entity.get() (once has fetch the item) a new attribute rating is calculated based off the numbers stored in the attributes previously mentioned. This derived state should not be saved/exist in the table.

I have played around with default and format etc but have had no joy

codingnuclei avatar Mar 02 '24 17:03 codingnuclei

Hey @codingnuclei, first of all, amazing initiative.

This is something that we've discussed in the past but haven't reached a final verdict on.

@jeremydaly @ThomasAribart wdyt?

naorpeled avatar Mar 03 '24 00:03 naorpeled

Hey - so I have added quite a few things now to: https://github.com/jeremydaly/dynamodb-toolbox/pull/689

I think it gives a real flavour of what I am proposing. It is pretty non-intrusive with patterns and existing code.

Would really value some feedback as to whether this is something the team wants within the toolbox.

😄

codingnuclei avatar Mar 09 '24 11:03 codingnuclei

This should be possible with format. It receives both the value of the attribute AND the entire object. You should be able to conditionally return based off of other attributes.

jeremydaly avatar Mar 17 '24 14:03 jeremydaly

Hey - yea i was initially hoping to use the format functionality but wasn't able to get it working.

From what I can see, the formatItem function loops over the response from the DB and matches the response fields against the entity schema:

https://github.com/jeremydaly/dynamodb-toolbox/blob/e527a1af512093b1d44add9944c8c5011e5f6feb/src/lib/formatItem.ts#L63

https://github.com/jeremydaly/dynamodb-toolbox/blob/e527a1af512093b1d44add9944c8c5011e5f6feb/src/lib/formatItem.ts#L108-L110

So my understanding is that if the field is not in the response Item then what is declared in the entity makes no difference...

Hoping I am missing something :)

codingnuclei avatar Mar 17 '24 17:03 codingnuclei

@jeremydaly any thoughts on the above? 😀

codingnuclei avatar Apr 05 '24 06:04 codingnuclei

@codingnuclei I'm thinking about adding readDefaults and readLinks at some point in the future as it is highly requested:

const schema = item({
  oneStar: number(),
  twoStar: number(),
  threeStar: number(),
  fourStar: number(),
  fiveStar: number(),
}).and(prevSchema => ({
  rating: number().optional().readLink<typeof prevSchema>(stars => getRating(stars))
})

Although I just realized that will probably require a breaking change on the required syntax first to add this edge case:

// prev
const attribute = string().required('always')

// next
const attribute = string().optional().readRequired() // or .putRequired(), or .updateRequired()

ThomasAribart avatar May 22 '25 09:05 ThomasAribart