WebExt Core
Proxy Service

Defining Services

There are several different ways to define a services, @webext-core/proxy-service works with all of them!

Class

Define a class whose methods are available in other JS contexts:

import { IDBPDatabase } from 'idb';

class TodosRepo {
  constructor(private db: Promise<IDBPDatabase>) {}

  async getAll(): Promise<Todo[]> {
    const db = await this.db;
    return await db.getAll('todos');
  }
}

Object

Objects can be used as services as well. All functions defined on the object are available in other contexts.

import { IDBPDatabase } from 'idb';

export interface TodosRepo {
  getAll(): Promise<Todo[]>;
}

export function createTodosRepo(dbPromise: Promise<IDBPDatabase>): TodosRepo {
  return {
    async getAll() {
      const db = await dbPromise;
      return await db.getAll('todos');
    },
  };
}

Function

If you only need to define a single function, you can!

import { IDBPDatabase } from 'idb';

export type GetAllTodos = () => Promise<Todo[]>;

export function createGetAllTodos(dbPromise: Promise<IDBPDatabase>) {
  return async () => {
    const db = await dbPromise;
    return await db.getAll('todos');
  };
}
const db = openDB('todos');
const getAllTodos = createGetAllTodos(db);

registerService('get-all-todos', getAllTodos);
const getAllTodos = createProxyService<GetAllTodos>('get-all-todos');

const todos = await getAllTodos();

Nested Objects

If you need to register "deep" objects containing multiple services, you can do that as well. You can use classes, objects, and functions at any level.

class TodosRepo {
  constructor(private db: Promise<IDBPDatabase>) {}

  async getAll(): Promise<Todo[]> {
    return (await this.db).getAll('todos');
  }
}

const createAuthorsRepo = (db: Promise<IDBPDatabase>) => ({
  async getOne(id: string): Promise<Todo[]> {
    return (await this.db).getAll('authors', id);
  },
});

export function createApi(db: Promise<IDBPDatabase>) {
  return {
    todos: new TodosRepo(db),
    authors: createAuthorsRepo(db),
  };
}
const db = openDB('todos', ...);
const api = createApi(db);

registerService("api", api);
const api = createProxyService<API>('api');

const todos = await api.todos.getAll();
const firstAuthor = await api.authors.getOne(todos.authorId);