seoscribe / jsearch

jsearch: a drop-in library for client-side search if you don't have a back-end.
BSD 3-Clause Clear License
2 stars 1 forks source link

Customise cache duration #11

Closed wnda closed 7 years ago

wnda commented 7 years ago

@loisatwood I noticed you're using new Date().toISOString.substring(0,10).replace(/\.|\-|\:/,'') to give you a unique identifier that will persist for the day the index was built, because you'd get something like: githubcom_20170521_idx

Which is fine, because every execution of jsearch will construct the string from the hostname and date and it will be equivalent on the day and the next day it will trigger the index to be built and not retrieved from localStorage, but I think we might want to open up flexibility regarding how long the cached index should persist.

The question is how to we accept a duration as a property of the config object? In seconds? Minutes? hours?

Also I noticed you already put in _no_cache but there's as yet no conditional logic built in to prevent caching if the variable is set to true. That's a two second fix so it's fine.

wnda commented 7 years ago

I've fixed the latter.

loisatwood commented 7 years ago

sorry about that 😌

i don't see the point in seconds/minutes cache time so hours?

i'm not sure how to customise the date string from the input. days are easy but hours would mean adding the time, which could be done obviously but is there not a better way?

wnda commented 7 years ago

Not really. Let's imagine you do this instead:

new Date().getTime()

Which yields a UNIX time stamp, something like 1495413911694 (in milliseconds since 1970)

Then as a default: _cache_duration = 8.64e+7 (one day in milliseconds)

Then instead of just checking whether localStorage has the right key, we do this:

// assuming _idx is set as you currently do, minus the `'_idx'` part which we don't *really* need
var _idx_d = +(_idx.replace((location.host.replace('.',''),''); // scrub the host and convert to number
var _d = new Date().getTime() // today as number

// difference less or equal to config cache threshold
if ( (_d - _idx_d) <= config.cache_duration ) {
  // use cache
} else {
  // don't use cache
}
loisatwood commented 7 years ago

better yet, instead of dealing with billions of milliseconds, we could say config.cache_duration 1e3 60 60 24

1495413911694 / 1000 / 60 / 60 / 24
milliseconds seconds minutes hours days
loisatwood commented 7 years ago

that would mean they pass in days or at least hours so the API is cleaner to use than entering enormous numbers.

wnda commented 7 years ago

We'll do hours, like DNS and everything else.

Okay that looks good to me.