Skip to content

Queries

The simplest way to read the items in a space is to use the space.db.query() method. It’s also possible to obtain strongly typed results as described below.

Untyped Queries

Once access is obtained to a space, objects can be retrieved:

import { Client } from '@dxos/client';
const client = new Client();
await client.initialize();
// Get a list of all spaces.
const spaces = client.spaces.get();
// Grab a space.
const space = spaces[0];
// Get all items.
const _allObjects = await space.db.query().run();
// Get items that match a filter.
const _tasks = await space.db.query({ type: 'task' }).run();
// Get items that match a predicate.
const _finishedTasks = await space.db
.query((doc: any) => doc.type === 'task' && doc.completed)
.run();

The result is an iterable collection of objects that can be used like an array.

Typed Queries

It’s possible to receive strongly typed results from query. This is done by declaring a type using Effect Schema for the objects in the space.

Consider this expression of schema declared with Effect Schema:

import { Schema } from 'effect';
import { Type } from '@dxos/echo';
export const Task = Schema.Struct({
name: Schema.String,
completed: Schema.optional(Schema.Boolean),
}).pipe(
Type.Obj({
typename: 'dxos.org/type/Task',
version: '0.1.0',
}),
);

Types can be used to make queries as well:

import { Client } from '@dxos/client';
import { Filter } from '@dxos/client/echo';
import { Task } from './schema';
const client = new Client({ types: [Task] });
await client.initialize();
// Get a list of all spaces.
const spaces = client.spaces.get();
// Grab a space.
const space = spaces[0];
// Get items that match a filter: type inferred from Task.filter().
const _tasks = await space.db.query(Filter.type(Task)).run();

Note the client.addTypes call which registers the generated types with the client.