Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[quick node token] add jwt #105

Merged
merged 3 commits into from
May 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions src/modules/gql-module/abortRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,16 @@ class AbortRequest<Data, ModifiedData> {
promise: AbortPromise<ModifiedData>
body: string
isAborted: boolean
requestId: string

constructor(url: RequestInfo | URL, abortRequestInit: AbortRequestInit<Data, ModifiedData>) {
const { onSuccess, onError, ...init } = abortRequestInit

this.body = init.body as string
this.isAborted = false
this.requestId = `${url}_${this.body}`

const pendingRequest = requestsQueue[this.body]
const pendingRequest = requestsQueue[this.requestId]

if (pendingRequest) {
pendingRequest.count += 1
Expand All @@ -55,7 +57,7 @@ class AbortRequest<Data, ModifiedData> {
return response.json().then((json) => Promise.reject(json))
})
.then((json) => {
requestsQueue[this.body] = undefined
requestsQueue[this.requestId] = undefined

if (json?.errors) {
throw new Error(json.errors[0].message)
Expand All @@ -69,7 +71,7 @@ class AbortRequest<Data, ModifiedData> {
return json?.data as Data
})
.catch((error) => {
requestsQueue[this.body] = undefined
requestsQueue[this.requestId] = undefined

if (typeof onError === 'function') {
onError(error)
Expand All @@ -78,7 +80,7 @@ class AbortRequest<Data, ModifiedData> {
return Promise.reject(error)
})

requestsQueue[this.body] = {
requestsQueue[this.requestId] = {
promise: this.request,
count: 1,
}
Expand Down Expand Up @@ -120,13 +122,13 @@ class AbortRequest<Data, ModifiedData> {
abort() {
this.isAborted = true

const count = requestsQueue[this.body]?.count || 0
const count = requestsQueue[this.requestId]?.count || 0

if (count > 1) {
(requestsQueue[this.body] as PendingRequest).count -= 1
(requestsQueue[this.requestId] as PendingRequest).count -= 1
}
else {
requestsQueue[this.body] = undefined
requestsQueue[this.requestId] = undefined
this.controller.abort()
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/modules/gql-module/utils/getRequestUrl.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { constants } from '../../../utils'
import localStorage from './local-storage'


const sessionErrorUrl = constants.sessionStorageNames.moduleErrorUrl
Expand All @@ -19,7 +20,7 @@ const getRequestUrl = (url: string | ReadonlyArray<string>): string => {

const [ primaryUrl, backupUrl ] = url

const hasError = sessionStorage.getItem(sessionErrorUrl) === primaryUrl
const hasError = localStorage.getSessionItem<string>(sessionErrorUrl) === primaryUrl

return hasError ? backupUrl : primaryUrl
}
Expand Down
170 changes: 170 additions & 0 deletions src/modules/gql-module/utils/local-storage/LocalStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
/* eslint-disable no-restricted-globals */
import MemoryStorage from './MemoryStorage'


const ffErrors = [
'NS_ERROR_FAILURE', // has max size
'NS_ERROR_FILE_CORRUPTED', // is crashed
'NS_ERROR_FILE_NO_DEVICE_SPACE',
]

class LocalStorage {
readonly memoryLocalStorage?: MemoryStorage
readonly memorySessionStorage?: MemoryStorage

constructor() {
if (!LocalStorage.isSupported(() => localStorage)) {
this.memoryLocalStorage = new MemoryStorage()
}

if (!LocalStorage.isSupported(() => sessionStorage)) {
this.memorySessionStorage = new MemoryStorage()
}
}

// we should check it like this, to avoid "Operation Insecure" errors
// add replace it with MemoryStorage
private static isSupported(getStorage: () => Storage) {
try {
const testKey = '__some_random_key_you_are_not_going_to_use__'
getStorage().setItem(testKey, testKey)
getStorage().removeItem(testKey)
return true
}
catch (error) {
return false
}
}

private getLocalStorage(): Storage {
return this.memoryLocalStorage || localStorage
}

private getSessionStorage(): Storage {
return this.memorySessionStorage || sessionStorage
}

private get<T>(name: string, storage: Storage): T | null {
try {
const value = storage.getItem(name)

return value && JSON.parse(value)
}
catch (err) {
// @ts-ignore
if (ffErrors.includes(err.name)) {
this.clear(storage)

return null
}

this.remove(name, storage) // remove invalid data

return null
}
}

private set<T>(name: string, value: T, storage: Storage) {
try {
storage.setItem(name, JSON.stringify(value))
}
catch (err) {
// @ts-ignore
if (ffErrors.includes(err.name)) {
this.clear(storage)
}
}
}

private remove(name: string, storage: Storage) {
try {
storage.removeItem(name)
}
catch (error) {
console.error(error, name)
}
}

// to show error alert only once
private corruptedAlertWasShowed = false

private clear(storage: Storage) {
// Firefox corrupted file error, try to clean up the storage, and ignore error
// https://stackoverflow.com/questions/18877643/error-in-local-storage-ns-error-file-corrupted-firefox
try {
storage.clear()
}
catch (error) {
// @ts-ignore
if (ffErrors.includes(error.name) && !this.corruptedAlertWasShowed) {
// eslint-disable-next-line max-len
alert('Oops, looks like your browser storage got corrupted. Follow the steps at https://support.mozilla.org/en-US/kb/storage to fix it.')

this.corruptedAlertWasShowed = true
}
}
}

private keys(storage: Storage): string[] {
const result: string[] = []

for (let i = 0; i < storage.length; i++) {
const key = storage.key(i)

if (key) {
result.push()
}
}

return result
}

// localStorage
public getItem<T>(name: string): T | null {
return this.get<T>(name, this.getLocalStorage())
}

public setItem<T>(name: string, value: T) {
this.set<T>(name, value, this.getLocalStorage())
}

public removeItem(name: string) {
this.remove(name, this.getLocalStorage())
}

public getKeys(): string[] {
return this.keys(this.getLocalStorage())
}

public clearAll() {
const storage = this.getLocalStorage()

this.clear(storage)
}

// session storage
public getSessionItem<T>(name: string): T | null {
return this.get(name, this.getSessionStorage())
}

public setSessionItem<T>(name: string, value: T) {
this.set(name, value, this.getSessionStorage())
}

public removeSessionItem(name: string) {
this.remove(name, this.getSessionStorage())
}

public getSessionKeys(): string[] {
return this.keys(this.getSessionStorage())
}

public clearAllSession() {
const storage = this.getSessionStorage()

this.clear(storage)
}
}


export default LocalStorage
36 changes: 36 additions & 0 deletions src/modules/gql-module/utils/local-storage/MemoryStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// This class is fallback storage when localStorage is blocked

class MemoryStorage implements Storage {
private storage = new Map<string, string | null>()

get length(): number {
return this.storage.size
}

key(index: number): string | null {
return Array.from(this.storage.keys())[index] || null
}

getItem(key: string): string | null {
if (this.storage.has(key)) {
return this.storage.get(key) as string | null
}

return null
}

setItem(key: string, value: string) {
this.storage.set(key, value)
}

removeItem(key: string) {
this.storage.delete(key)
}

clear(): void {
this.storage.clear()
}
}


export default MemoryStorage
4 changes: 4 additions & 0 deletions src/modules/gql-module/utils/local-storage/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import LocalStorage from './LocalStorage'


export default new LocalStorage()
7 changes: 4 additions & 3 deletions src/modules/gql-module/utils/saveErrorUrlToSessionStorage.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { constants } from '../../../utils'
import localStorage from './local-storage'


const sessionErrorUrl = constants.sessionStorageNames.moduleErrorUrl

const saveErrorUrlToSessionStorage = (url: string) => {
const currentErrorUrl = sessionStorage.getItem(sessionErrorUrl)
const currentErrorUrl = localStorage.getSessionItem<string>(sessionErrorUrl)

if (currentErrorUrl !== url) {
sessionStorage.setItem(sessionErrorUrl, url)
localStorage.setSessionItem(sessionErrorUrl, url)

setTimeout(() => {
sessionStorage.removeItem(sessionErrorUrl)
localStorage.removeSessionItem(sessionErrorUrl)
}, 60 * 60 * 1000) // 1 hour
}
}
Expand Down
9 changes: 8 additions & 1 deletion src/types/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,20 @@ declare global {
send: () => any
}

type UrlWithHeaders = {
url: string
headers: Record<string, string>
}

type Web3Endpoints = string | string[] | UrlWithHeaders[]

type Options = {
network: Network
provider?: Provider
endpoints?: {
api?: string
subgraph?: string | ReadonlyArray<string>
web3?: string | string[]
web3?: Web3Endpoints
}
}

Expand Down
Loading
Loading