Last active
December 1, 2022 11:26
-
-
Save alanshaw/ea4bd2b0ab215ade696eac1300be577d to your computer and use it in GitHub Desktop.
w3access agent refactor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Goals: | |
// 1. Decouple store from agent | |
// 2. Simplify agent creation | |
// 3. Agent governs data format not store | |
// 4. Initialization of agent, not store | |
// 5. DRY initialization in agent, not repeated in each store impl | |
/** | |
* @param {AgentData} [data] Agent data | |
* @param {object} [options] | |
* @param {(data: AgentData) => Promise<void>} [options.save] Called when agent | |
* data changes and should be persisted. | |
*/ | |
Agent.create = async (data, options = {}) => { | |
const agent = new Agent(data, options) | |
// if data is null/undefined the agent is not initialized | |
if (!agent.isInitialized) await agent.init() | |
return agent | |
} | |
Agent.fromStore = async (store, options = {}) => { | |
await store.open() | |
const data = await store.load() // { ... } or null/undefined | |
return Agent.create(data, { ...options, save: data => store.save(data) }) | |
} | |
// Basically, when agent calls `this.store.save(this.#data)` it now calls | |
// `this.#options.save(this.#data)`. | |
/////////////////////////////////////////////////////////////////////////////// | |
// In regular use: | |
const store = new StoreIndexedDB() | |
const agent = await Agent.fromStore(store) | |
// Then StoreMemory can be deleted, since the agent already stores all data in | |
// memory. It's equivalent to: | |
const agent = await Agent.create() | |
// or | |
const agent = new Agent() | |
await agent.init() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment