withPlugins
import { withPlugins } from '@signaldb/core'withPlugins(collection, ...plugins) installs plugins on a collection. A plugin adds methods to the collection, and a package can ship one to extend collections without a change to SignalDB itself.
import { Collection, withPlugins } from '@signaldb/core'
const Posts = withPlugins(
new Collection<Post>('posts', dataAdapter, { reactivity }),
newest(),
// …further plugins
)
const post = await Posts.newest()newest() is the plugin written below. For a complete plugin, see @signaldb/search, which adds a reactive search() method.
withPlugins returns the collection you passed in. Only its type differs, because it knows about the added methods. Use the returned value, even though it is the same object.
- The plugins are installed in the order they are passed.
- A plugin that would add a method the collection already has, either as one of its own members or from a plugin installed before, makes
withPluginsthrow. dispose()disposes the plugins first, one after another, while the collection is still usable, and the collection afterwards.
Writing a plugin
A plugin is a function that receives the collection and a context, and returns the methods it adds along with an optional dispose function.
import type { CollectionPlugin } from '@signaldb/core'
type CollectionPlugin<Methods extends object> = (
collection: Collection<any, any, any, any>,
context: { reactivity?: ReactivityAdapter },
) => {
methods: Methods,
dispose?: () => void | Promise<void>,
}context.reactivity is the collection's reactivity adapter, for plugins whose methods are reactive themselves.
A method that needs the collection's item types declares the collection through a this parameter. TypeScript then resolves the types at the call site, so they are correct even for a collection created with an explicit item type.
import type { Collection, CollectionPlugin } from '@signaldb/core'
type AnyCollection = Collection<any, any, any, any>
type ItemOf<C> = C extends Collection<any, any, any, infer U> ? U : never
const newest = (): CollectionPlugin<{
newest<C extends AnyCollection>(this: C): Promise<ItemOf<C> | undefined>,
}> => collection => ({
methods: {
newest: () => collection.findOne({}, { sort: { createdAt: -1 }, async: true }),
},
})
const Posts = withPlugins(new Collection<Post>('posts', dataAdapter), newest())
const post = await Posts.newest() // Post | undefinedThe methods are called on the collection, but they should not rely on this at runtime. Use the collection argument instead, as above.