|
| 1 | +import * as yup from "yup"; |
| 2 | + |
| 3 | +const DEFAULTS_KEY = 'defaults'; |
| 4 | +const RECORDED_KEY = 'recorded'; |
| 5 | + |
| 6 | +const defaultsSchema = yup.object({ |
| 7 | + startTime: yup.string().required(), |
| 8 | + target: yup.string().required(), |
| 9 | +}).required(); |
| 10 | + |
| 11 | +const recordedSchema = yup.object({ |
| 12 | + recorded: yup.string().required(), |
| 13 | + updated: yup.number().required().nullable() |
| 14 | +}).required(); |
| 15 | + |
| 16 | +function getJsonValue(key, defaultValue = {}) { |
| 17 | + const item = localStorage.getItem(key); |
| 18 | + if (item != null) { |
| 19 | + try { |
| 20 | + const data = JSON.parse(item); |
| 21 | + if (typeof data === 'object') { |
| 22 | + return data; |
| 23 | + } |
| 24 | + } catch (e) { |
| 25 | + localStorage.removeItem(key); |
| 26 | + return defaultValue; |
| 27 | + } |
| 28 | + } |
| 29 | + return defaultValue; |
| 30 | +} |
| 31 | + |
| 32 | +export function getStoredDefaults() { |
| 33 | + const value = getJsonValue(DEFAULTS_KEY); |
| 34 | + try { |
| 35 | + return defaultsSchema.validateSync(value); |
| 36 | + } catch (e) { |
| 37 | + return {}; |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +export function setStoredDefaults(data) { |
| 42 | + localStorage.setItem(DEFAULTS_KEY, JSON.stringify(data)); |
| 43 | +} |
| 44 | + |
| 45 | +export function getStoredRecordedTime() { |
| 46 | + const info = getJsonValue(RECORDED_KEY, { recorded: '', updated: null }); |
| 47 | + try { |
| 48 | + const data = recordedSchema.validateSync(info); |
| 49 | + if (data.updated != null) { |
| 50 | + const startOfDay = new Date(); |
| 51 | + startOfDay.setHours(0, 0, 0, 0); |
| 52 | + |
| 53 | + if (data.updated < startOfDay.valueOf()) { |
| 54 | + return ''; |
| 55 | + } |
| 56 | + } |
| 57 | + return data.recorded; |
| 58 | + } catch (e) { |
| 59 | + return ''; |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +export function setStoredRecordedTime(recorded) { |
| 64 | + localStorage.setItem(RECORDED_KEY, JSON.stringify({ recorded, updated: new Date().valueOf() })); |
| 65 | +} |
0 commit comments