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.

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

import { Client } from '@dxos/client';
import { Filter } from '@dxos/echo';
import { Expando } from '@dxos/schema';
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(Filter.everything()).run();
// Get items that match a filter.
const _tasks = await space.db
.query(Filter.type(Expando.Expando, { type: 'task' }))
.run();
// Get items that match a predicate.
const _finishedTasks = await space.db
.query(Filter.type(Expando.Expando, { type: 'task', completed: true }))
.run();

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

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 * as Schema from 'effect/Schema';
import { Type } from '@dxos/echo';
export const Task = Schema.Struct({
name: Schema.String,
completed: Schema.optional(Schema.Boolean),
}).pipe(
Type.object({
typename: 'org.dxos.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.