Sharing attribute definitions #516
-
In the context of Single Table design, we have two toolbox Entities that share the same attributes excluding the PK and SK. What I would like to do is define the shared attributes once and then refer to the shared definition in the two Entities that need them: Something like this: const sharedAttributes: AttributeDefinitions = {
attr1: { type: 'string', required: true },
attr2: { type: 'number', required: false },
attrn: { type: 'number', required: false }
}
const entity1 = new Entity({
name: 'Entity1',
attributes: {
PK: { partitionKey: true, default: 'xxxx' },
... sharedAttributes
}
})
const entity2 = new Entity({
name: 'Entity2',
attributes: {
PK: { partitionKey: true, default: 'yyyy' },
... sharedAttributes
}
} When I use the above technique, I do not get any type checking when trying to Put an item. Moreover, when I hover over the Entity, it doesn't now about the shared attributes. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi, this is because the variable is of type
const sharedAttributes = {
attr1: { type: 'string', required: true },
attr2: { type: 'number', required: false },
attrn: { type: 'number', required: false }
} as const satisfies AttributeDefinitions
import { type AttributeDefinition } from 'dynamodb-toolbox/dist/classes/Entity'
export type AsAttributeDefinition<
TObject extends Record<PropertyKey, unknown>
> = Record<keyof TObject, AttributeDefinition>
// sample usage
type UserProfile = {
billingInfo?: BillingInfo
cognitoUsername: string
email: string
firstName: string
lastName: string
organizationId?: string
tenantId: string
userId: string
}
const userProfileAttributes: AsAttributeDefinition<UserProfile> = {
billingInfo: { type: 'map' },
cognitoUsername: { type: 'string' },
email: { type: 'string' },
firstName: { type: 'string' },
lastName: { type: 'string' },
organizationId: { type: 'string' },
tenantId: { type: 'string' },
userId: { type: 'string' },
} I personally prefer the second method because I'll create my own types for every db entity. |
Beta Was this translation helpful? Give feedback.
Hi, this is because the variable is of type
AttributeDefinitions
and the specific type is lost. There are two options to do this in a nice way.as const
andsatisfies
operator introduced in typescript 4.9