FIX: fully rely on keyValueStore to prevent error (#12)

* FIX: fully rely on keyValueStore to prevent error

The component was generating errors for some users due to direct access to `localStorage`:

```
TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at Object.expireOldValues (https://d3bpeqsaub0i6y.cloudfront.net/theme-javascripts/33bf35dc19b970a42f8c1e7d57d8cc72d6205bbd.js?__ws=meta.discourse.org:157:14)
    at Object.initialize (https://d3bpeqsaub0i6y.cloudfront.net/theme-javascripts/33bf35dc19b970a42f8c1e7d57d8cc72d6205bbd.js?__ws=meta.discourse.org:193:12)
    at o.initialize (https://d11a6trkgmumsb.cloudfront.net/assets/discourse-2bd9a9aa6b5c9cbee990a03159f5bff41fe503fe74814c3b66b3770876913dd5.gz.js:68:38)
```

This commits removes old unnecessary code using cookies and uses latest API from core `removeKeys`. Old discourse instances will just not evict old keys which is a minor annoyance.

* linting
This commit is contained in:
Joffrey JAFFEUX 2022-08-22 00:25:50 +02:00 committed by GitHub
parent faf88c2209
commit be75773375
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 7 additions and 31 deletions

View File

@ -1,7 +1,6 @@
import showModal from "discourse/lib/show-modal";
import { withPluginApi } from "discourse/lib/plugin-api";
import { debounce, later } from "@ember/runloop";
import cookie, { removeCookie } from "discourse/lib/cookie";
const VALID_TAGS =
"h1, h2, h3, h4, h5, h6, p, code, blockquote, .md-table, li p";
@ -66,36 +65,15 @@ function buildSelect(key, placeholder) {
export default {
name: "discourse-placeholder-theme-component",
// TODO: Remove once this change has been live for a few months
migrateCookiesToKeyValueStore() {
const cookies = document.cookie.split("; ");
const oldPlaceholderCookies = [];
for (let i = 0, l = cookies.length; i < l; i++) {
let parts = cookies[i].split("=");
if (parts[0].startsWith(STORAGE_PREFIX)) {
oldPlaceholderCookies.push(parts[0]);
}
}
for (const key of oldPlaceholderCookies) {
const value = cookie(key);
this.setValue(key, value);
removeCookie(key);
}
},
expireOldValues() {
const now = Date.now();
Object.keys(window.localStorage)
.filter((k) => k.startsWith(STORAGE_PREFIX))
.forEach((k) => {
const data = this.keyValueStore.getObject(k);
if (!data?.expires || data.expires < now) {
this.removeValue(k);
}
});
this.keyValueStore.removeKeys?.((k, v) => {
if (!k.includes(STORAGE_PREFIX)) {
return false;
}
return !v?.expires || v.expires < now;
});
},
getValue(key) {
@ -123,8 +101,6 @@ export default {
initialize(container) {
this.keyValueStore = container.lookup("service:key-value-store");
this.migrateCookiesToKeyValueStore();
this.expireOldValues();
withPluginApi("0.8.7", (api) => {