From e6c9b35ab402df7d9ebb82306131fc30d0a8b893 Mon Sep 17 00:00:00 2001 From: Yanbowen <349952469@qq.com> Date: Tue, 23 Nov 2021 09:57:59 +0800 Subject: [PATCH] =?UTF-8?q?feat(storage):=20local=E5=AD=98=E5=82=A8?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=9C=89=E6=95=88=E6=9C=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/storage/local.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/utils/storage/local.ts b/src/utils/storage/local.ts index c042eac3..7a50404d 100644 --- a/src/utils/storage/local.ts +++ b/src/utils/storage/local.ts @@ -1,12 +1,21 @@ -export function setLocal(key: string, value: unknown) { - const json = JSON.stringify(value); +/** 默认缓存期限为7天 */ +const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7; + +export function setLocal(key: string, value: unknown, expire: number | null = DEFAULT_CACHE_TIME) { + const json = JSON.stringify({ value, expire: expire !== null ? new Date().getTime() + expire * 1000 : null }); window.localStorage.setItem(key, json); } export function getLocal(key: string) { const json = window.localStorage.getItem(key); if (json) { - return JSON.parse(json) as T; + const data = JSON.parse(json); + const { value, expire } = data; + /** 在有效期内直接返回 */ + if (expire === null || expire >= Date.now()) { + return value as T; + } + removeLocal(key); } return null; }