mirror of
https://github.com/GiriNeko/YesPlayMusic.git
synced 2025-12-17 05:38:04 +00:00
test: 改进cookie.ts 和 增加cookie单元测试
This commit is contained in:
parent
0c89b4aa53
commit
13281d3f08
4 changed files with 280 additions and 19 deletions
|
|
@ -1,12 +1,63 @@
|
|||
import Cookies from 'js-cookie'
|
||||
import Cookies, { CookieAttributes } from 'js-cookie'
|
||||
|
||||
interface Cookie {
|
||||
key: string
|
||||
value: string
|
||||
options?: CookieAttributes
|
||||
}
|
||||
|
||||
export function parseCookies(cookie: string): Cookie[] {
|
||||
const cookies: Cookie[] = []
|
||||
let tmpCookie: Cookie | null = null
|
||||
cookie.split(';').forEach(item => {
|
||||
const splittedItem = item.split('=')
|
||||
if (splittedItem.length !== 2) return
|
||||
|
||||
const key = splittedItem[0].trim()
|
||||
const value = splittedItem[1].trim()
|
||||
|
||||
if (key.toLowerCase() === 'expires') return
|
||||
if (key.toLowerCase() === 'max-age') {
|
||||
const expires = Number(value) / 60 / 60 / 24
|
||||
if (isNaN(expires)) return
|
||||
tmpCookie = {
|
||||
...((tmpCookie as Cookie) ?? {}),
|
||||
options: {
|
||||
...tmpCookie?.options,
|
||||
expires: expires,
|
||||
},
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (key.toLowerCase() === 'path') {
|
||||
tmpCookie = {
|
||||
...((tmpCookie as Cookie) ?? {}),
|
||||
options: {
|
||||
...tmpCookie?.options,
|
||||
path: value,
|
||||
},
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (tmpCookie) cookies.push(tmpCookie)
|
||||
|
||||
tmpCookie = {
|
||||
key,
|
||||
value,
|
||||
}
|
||||
})
|
||||
|
||||
if (tmpCookie) cookies.push(tmpCookie)
|
||||
|
||||
return cookies
|
||||
}
|
||||
|
||||
export function setCookies(string: string) {
|
||||
const cookies = string.replace(/;.*?HTTPOnly.*?;/g, ';;').split(';;')
|
||||
cookies.map(cookie => {
|
||||
const cookieKeyValue = cookie.split(';')[0].split('=')
|
||||
const [key, value] = cookieKeyValue
|
||||
// store.account.cookies[key] = value
|
||||
Cookies.set(key, value, { expires: 3650 })
|
||||
const cookies = parseCookies(string)
|
||||
cookies.forEach(cookie => {
|
||||
Cookies.set(cookie.key, cookie.value, cookie.options)
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -17,3 +68,13 @@ export function getCookie(key: string) {
|
|||
export function removeCookie(key: string) {
|
||||
Cookies.remove(key)
|
||||
}
|
||||
|
||||
export function removeAllCookies() {
|
||||
const cookies = document.cookie.split(';')
|
||||
|
||||
cookies.forEach(cookie => {
|
||||
const splitted = cookie.split('=')
|
||||
const name = splitted[0].trim()
|
||||
document.cookie = `${name}=;max-age=0`
|
||||
})
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue