amplify
amplify copied to clipboard
amplify.request.cache._key is sometimes doesn't resulting unique value
To reproduce this issue please try this at browser console:
amplify.request.cache._key('ajax1', '/api/opqrstu/opqrstu-project-1/project/get')
it will resulting "request-ajax1-992640007"
now try with this:
amplify.request.cache._key('ajax1', '/api/abcdefg/abcdefg-project-1/project/get')
then you'll get same result "request-ajax1-992640007"
Furthermore,
amplify.request.cache._key('foo', 'foo?a=1&b=2') === amplify.request.cache._key('foo', 'foo?a=2&b=1')
evaluates to true
On more: 'x' and 'xxxxxxxxx' gets the same hashvalue, because 'xxxx' XOR 'xxxx' evaluates to zero! Furthermore it seems the algorithm doesn't takes care of unicode - all values shifted by 8 bits.
My suggestions is to use/override the _key function with a better one (e.g. java hashCode or crc32):
amplify.request.cache._key = function (resourceId, url, data) {
function hashCode(s) {
var hash = 0, i, chr, len = s.length;
if (len === 0) {
return hash;
}
for (i = 0; i < len; i++) {
chr = s.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0;
}
return hash;
};
return 'request-' + resourceId + '-' + hashCode(url + data).toString(16);
};
Yah, seriously this hash needs to be changed. Within a couple of hours of trying out amplify I ran into puzzling, buggy behavior that indeed turned out to be cache key collisions.