Best way to implement multiple Schemas in attribute (strategy pattern) #1277
Replies: 1 comment 3 replies
-
I'm not sure exactly what you are talking about. So I'm going to be making a few assumptions in this answer. You have 1 model in Dynamoose (which represents 1 table in DynamoDB). And you want to save objects that look like the example you gave, as well as objects that look like:
In this case you can take advantage of the fact that the Therefore, you could do something like: const Discount = dynamoose.model("Discount", [
new dynamoose.Schema({
"code": {
"type": String,
"required": true
},
"resolver": {
"type": "Constant",
"settings": {
"value": "orderFractionOff"
}
},
"params": {
"type": Object,
"schema": {
"fraction": Number
}
}
}),
new dynamoose.Schema({
"code": {
"type": String,
"required": true
},
"resolver": {
"type": "Constant",
"settings": {
"value": "orderDollarOff"
}
},
"params": {
"type": Object,
"schema": {
"amount": Number
}
}
})
]); This will cause Dynamoose to automatically pick the best schema available based on the document you passed in. However, this almost seems over-engineered to me. There is no reason you can't just use Therefore, another option would be to do something like the following: const Discount = dynamoose.model("Discount", new dynamoose.Schema({
"code": {
"type": String,
"required": true
},
"resolver": [{
"type": "Constant",
"settings": {
"value": "orderFractionOff"
}
}, {
"type": "Constant",
"settings": {
"value": "orderDollarOff"
}
}],
"params": {
"type": Object,
"schema": {
"amount": Number
}
}
})); This will use a single schema, and only allow 2 values for |
Beta Was this translation helpful? Give feedback.
-
Hi everyone! I'm trying to implement some sort of strategy pattern for a discount code feature in an ecommerce.
Roughly, each discount code has a
resolver
field, which is a string specifying the name of the function to apply at runtime to calculate the discount amount, and aparams
field, which gives this resolver the required parameters to run properly.Example: there's a resolver called
orderFractionOff
that receives afraction
parameter to substract it from the order total price. So the discount entry in the table looks like this:My question is, how can I validate the correct
params
schema depending on the value ofresolver
. My options right now are: (1) Saveparams
as unknown and validate independently before creation of discount code and everytime the resolver function is executed. (2) Pass multiple possible schemas atparams
schema definition and let Dynamoose figure it out, but we'd have to make sure each resolver has params with different names or types, which is too implicit and a risk if the number of resolvers grows too much.I faced the same challenge implementing CQRS a while back, but the number of events was very small so we just saved unknown and carried on.
Thanks for your time :)
Beta Was this translation helpful? Give feedback.
All reactions