dynamodb-toolbox: Default does not support function (for conditionnal need)

Hi,

I tried to use the “default” option with function call because I needed to use a condition to choose the default value but the function is not evaluated and its code content is stored in DDB instead:

Entity configuration:

const INVITATION_DATA_TYPE = 'INVITATION';
const InvitationEntity = new Entity({
	// Specify entity name
	name: INVITATION_DATA_TYPE,
	// Assign it to our table
	table: DataTable,
	timestamps: false,
	typeAlias: 'dataType',
	// Define attributes
	attributes: {
		farmId: { partitionKey: true }, // flag as partitionKey
		rangeKey: { hidden: true, sortKey: true, default: (data) => `${INVITATION_DATA_TYPE}#${data.invitationId}` }, // flag as sortKey and mark hidden
		invitationId: { type: 'string', map: 'dataId' },
		email: { type: 'string' },
		hashCode: { type: 'string' },
		status: { type: 'string' },
		timestamp: { type: 'number' },
		createdAt: {
			type: 'string', 
			default: (data) => {
				if (data.createdAt) {
					return data.createdAt
				} else {
					return new Date().toISOString()
				}
			}
		},
		modifiedAt: { type: 'string', default: (data) => new Date().toISOString() },
	},
});

And in DDB, I get:

{
  "createdAt": "(data) => {\n\t\t\t\tif (data.createdAt) {\n\t\t\t\t\treturn data.createdAt\n\t\t\t\t} else {\n\t\t\t\t\treturn new Date().toISOString()\n\t\t\t\t}\n\t\t\t}",
  "dataId": "5fbea3ed-cd7f-4c0f-aefe-d6334c864d07",
  "dataType": "INVITATION",
  "email": "opt411@gmail.com",
  "hashCode": "03d428236b80cbbbbec45f2a6d31d2a955f2f7bdefb80fa0f05cda000ae0db76f991eb7520d0f1bb79d2cfda51b14fd5130c317847447bab70d2725e8747040e",
  "hashKey": "bf30c17d-5ea4-4e20-ab65-da2bd8a6187f",
  "modifiedAt": "2020-12-29T23:30:36.974Z",
  "rangeKey": "INVITATION#5fbea3ed-cd7f-4c0f-aefe-d6334c864d07",
  "status": "sent",
  "timestamp": 1609284636970
}

Maybe it is a configuration on my side?

Thank you,

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Comments: 15 (8 by maintainers)

Most upvoted comments

Hi @OlivierPT. Thanks for noticing this. I understand your use case, and you should be able to set the alias and the attribute name to the same thing. I will investigate this and see if we can relax the constraint.

If you want the attribute on the dynamodb item to be changed from ‘_ct’ to ‘createdAt’ then you want to set created.

If you want the attribute on the parsed entity to be changed from ‘created’ to ‘createdAt’ then you want to set createdAlias.

Im not sure why you would want the former (remember attribute names contribute to item size) but I think you are looking for the latter.

Incidentally, I reported a potential bug (#112) a day ago where ‘created’ isn’t being set. I’m working on getting to the bottom of it. Maybe this is your issue?

Actually, the reason is mainly for understanding… But you are right that ‘createdAlias’ is the most optimised solution. For now, I decided to go for this one…