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

`updateLink` typing is confusing to use

Open lucas-subli opened this issue 6 months ago • 0 comments

When using the .updateLink() function, verifying that an attribute (or even worse, a nested attribute) is updating is confusing.

Example 1:

I have a tracker of a pokemons last battle, and I track a date they will get sad for lack of battle.

I want the sad date to be updated when the last battle date updates.

const pokeSchema = schema({
	eggId: string().key().savedAs('pk'),
	trainer: string().key().savedAs('sk'),
	lastMatch: string(),
}).and((prevSchema) => ({
	// Pokemons get sad if they dont battle for 10 days
	sadAt: string()
		.putLink<typeof prevSchema>(({ lastMatch }) => {
			const sadDate = new Date(lastMatch);
			sadDate.setDate(sadDate.getDate() + 10);
			return sadDate.toISOString();
		})
		.updateLink<typeof prevSchema>(({ lastMatch }) => {
			if (lastMatch) {
				const sadDate = new Date(lastMatch);
				sadDate.setDate(sadDate.getDate() + 10);
				return sadDate.toISOString();
			}
			return;
		}),
}));

This won't work because the typing is weird:

image

Example 2:

I have a pokemon with two types, and I setup a search Global secondary index to search by type.

However the types are on a nested object. Since nested objects can be $SET the typing gets even more confusing.

const attributesSchema = map({
	type1: string(),
	type2: string(),
	hp: number(),
	attack: number(),
	defense: number(),
});

const pokeSchema = schema({
	pokemonId: string().key().savedAs('pk'),
	trainer: string().key().savedAs('sk'),
	attributes: attributesSchema,
}).and((prevSchema) => ({
	searchByType: string()
		.hidden()
		.putLink<typeof prevSchema>(({ attributes }) => {
			return `${attributes.type1}#${attributes.type2}`;
		})
		.updateLink<typeof prevSchema>(({ attributes }) => {
			if (attributes) {
				return `${attributes.type1}#${attributes.type2}`;
			}
			return;
		})
		.savedAs('gsipk'),
}));

image

Sugestion

I have been using checks with typeof as my use case allows it, however on the second case my code would fails if $set was used to update the attributes instead of a normal object.

I am not sure on how to handle this case.

Since I don´t think there is a better in-code solution for this problem, I think that some examples on how to handle a few of those cases on the documentation would be helpful.

lucas-subli avatar Aug 23 '24 14:08 lucas-subli