Collection items is not unique
Grawl opened this issue · comments
I trying to create a collection, and items data is not unique.
Here is a quick example on how to reproduce this:
/services/get/collection.js
module.exports = {
path: '/collection',
collection: true,
cache: false,
template: {
random: Math.random(),
}
}
package.json
{
"private": true,
"scripts": {
"services": "dyson services"
},
"devDependencies": {
"dyson": "^1.0.2",
}
}
Run services
:
/usr/local/bin/node /usr/local/lib/node_modules/npm/bin/npm-cli.js run services
> project@0.0.0 services /path/to/project
> dyson services
Registering GET service at /collection
Dyson listening at port: 3000
Resolving response for GET /collection
And got this:
[{"random":0.8456052458929002},{"random":0.8456052458929002},{"random":0.8456052458929002},{"random":0.8456052458929002},{"random":0.8456052458929002},{"random":0.8456052458929002},{"random":0.8456052458929002}]
Items is not unique as you can see. All the same.
Something is missing in my code?
You should make it dynamic, a function (it's evaluated only once now and set as the value).
@webpro thank you, now it's unique:
template: {
random: ()=> Math.random(),
}
[{"random":0.44458511570855785},{"random":0.9926197994943111}]
But can I make all items in template to be unique? Like this:
template: () => {
return {
random: Math.random(),
}
}
I tried to do this, but it not makes items values unique.
Are you saying that with the second example, you get the same value for random
each time?
Yes.
But it's a fixed value, not a function anymore, as I've explained above. It evaluates the template, and if collection === true
it puts this in an array x times. Going to close this for now, feel free to discuss further.
Okay I got it. For me, it was unexpected that g.id
from get/users.js
from dyson-demo return unique value for each collection item, but not Math.random()
The difference between g.id
and Math.random()
is that the former is a reference to a function (which dyson will execute), and the latter is a function call which will pre-populate the property with the return value.