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

feat: extension background storage #98

Merged
merged 4 commits into from
Feb 19, 2024
Merged
Changes from 1 commit
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
Next Next commit
extension storage config, sync background storage with popup context …
…storage
ionutanin committed Feb 13, 2024
commit ab9126080b84ead02056cd49325b75afabfc1dd1
10 changes: 9 additions & 1 deletion src/background/Background.ts
Original file line number Diff line number Diff line change
@@ -3,23 +3,31 @@ import { runtime, tabs } from 'webextension-polyfill'
import { PaymentFlowService } from '@/background/grantFlow'

import getSendingPaymentPointerHandler from '../messageHandlers/getSendingPaymentPointerHandler'
import getStorageData from '../messageHandlers/getStorageData'
import isMonetizationReadyHandler from '../messageHandlers/isMonetizationReadyHandler'
import setIncomingPointerHandler from '../messageHandlers/setIncomingPointerHandler'
import { defaultData } from './StorageService'
import { tabChangeHandler, tabUpdateHandler } from './tabHandlers'

class Background {
private messageHandlers: any = [
isMonetizationReadyHandler,
setIncomingPointerHandler,
getSendingPaymentPointerHandler,
getStorageData,
]
private subscriptions: any = []
// TO DO: remove these from background into storage or state & use injection
grantFlow: PaymentFlowService | null = null
spentAmount: number = 0
paymentStarted = false

constructor() {}
constructor({ storageService }: any) {
storageService
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

initialisation of data should be done when create a new instance of storage, because it's a singleton

.set('data', defaultData)
.then(() => console.log('Default data stored successfully'))
.catch((error: any) => console.error('Error storing data:', error))
}

subscribeToMessages() {
this.subscriptions = this.messageHandlers.map((handler: any) => {
2 changes: 2 additions & 0 deletions src/background/BackgroundContainer.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { asClass, createContainer } from 'awilix'

import Background from './Background'
import StorageService from './StorageService'

const BackgroundContainer = createContainer()

BackgroundContainer.register({
Background: asClass(Background).singleton(),
storageService: asClass(StorageService).singleton(),
// TODO - add injectable services
})

53 changes: 53 additions & 0 deletions src/background/StorageService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import browser from 'webextension-polyfill'

export interface IStorageService {
set(_key: string, _value: any): Promise<void>
get(_key: string): Promise<any>
}

export interface ExtensionStorageData {
amount: number
amountType: {
recurring: boolean
}
rateOfPay: number
wmEnabled: boolean
accessTokenQuote: string
accessTokenOutgoing: string
refreshToken: string
manageUrl: string
}

export const defaultData: ExtensionStorageData = {
amount: 0,
amountType: {
recurring: true,
},
rateOfPay: 0.36,
wmEnabled: true,
accessTokenQuote: '',
accessTokenOutgoing: '',
refreshToken: '',
manageUrl: '',
}

class StorageService {
async get(key: string): Promise<ExtensionStorageData | undefined> {
try {
const result = await browser.storage.sync.get(key)
return result[key] as ExtensionStorageData
} catch (error) {
throw new Error(`Error retrieving data: ${error}`)
}
}

async set(key: string, value: ExtensionStorageData): Promise<void> {
try {
await browser.storage.sync.set({ [key]: value })
} catch (error) {
throw new Error(`Error saving data: ${error}`)
}
}
}

export default StorageService
13 changes: 13 additions & 0 deletions src/messageHandlers/getStorageData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import Background from '@/background/Background'

const getStorageData = async (background: Background) => {
console.log('getStorageData background', background)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I get this is a dummy example, but to show case the usage, you can invoke the background.storageService and return the result

return {
type: 'SUCCESS',
data: {
someData: 'data',
},
}
}

export default { callback: getStorageData, type: 'GET_STORAGE_DATA' }
15 changes: 14 additions & 1 deletion src/providers/popup-context.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import React, { createContext, useState } from 'react'
import React, { createContext, useEffect, useState } from 'react'

import { sendMessage } from '@/utils/sendMessages'

import { PopupContextValue, TPopupContext } from './providers.interface'

@@ -27,6 +29,17 @@ export const PopupContext = createContext<PopupContextValue>({
export const PopupProvider: React.FC<IProps> = ({ children }) => {
const [data, setData] = useState<TPopupContext>(defaultData)

const getStorageData = async () => await sendMessage({ type: 'GET_STORAGE_DATA' })

Copy link
Contributor

@dianafulga dianafulga Feb 14, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there are no dependencies, so it can be moved outside the component, maybe a utils file associated with the popup-context provider (maybe group under a folder)

useEffect(() => {
;(async () => {
const storageData = await getStorageData()
console.log('storageData xxx', storageData)
// setData(storageData.data)
})()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

return <PopupContext.Provider value={{ data, setData }}>{children}</PopupContext.Provider>
}

2 changes: 2 additions & 0 deletions src/types/message.d.ts
Original file line number Diff line number Diff line change
@@ -10,6 +10,8 @@ declare type EXTMessageType =
| 'STOP_PAYMENTS'
| 'PAYMENT_SUCCESS'
| 'PAUSE_PAYMENTS'
| 'GET_STORAGE_DATA'
| 'SET_STORAGE_DATA'

declare type EXTMessage<T = any> = {
type: EXTMessageType