rhizome/src/example-app.ts

72 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-12-23 17:29:38 -06:00
import {Collection} from "./collection";
import {HTTP_API_ENABLE} from "./config";
import {runDeltas} from "./deltas";
import {runHttpApi} from "./http-api";
import {Entity} from "./object-layer";
2024-12-23 17:29:38 -06:00
import {askAllPeersForDeltas, subscribeToSeeds} from "./peers";
import {bindPublish, } from "./pub-sub";
import {bindReply, runRequestHandlers} from "./request-reply";
2024-12-23 17:29:38 -06:00
import {TypedCollection} from "./typed-collection";
2024-12-21 21:16:18 -06:00
// As an app we want to be able to write and read data.
// The data is whatever shape we define it to be in a given context.
// So we want access to an API that is integrated with our declarations of
// e.g. entities and their properties.
2024-12-23 17:29:38 -06:00
type User = {
2024-12-21 21:16:18 -06:00
id?: string;
name: string;
nameLong?: string;
email?: string;
age: number;
};
(async () => {
2024-12-23 17:29:38 -06:00
const users = new TypedCollection<User>();
2024-12-22 14:38:01 -06:00
2024-12-23 17:29:38 -06:00
await bindPublish();
await bindReply();
if (HTTP_API_ENABLE) {
2024-12-23 17:29:38 -06:00
runHttpApi({users});
2024-12-21 21:16:18 -06:00
}
runDeltas();
runRequestHandlers();
2024-12-22 09:13:44 -06:00
await new Promise((resolve) => setTimeout(resolve, 500));
2024-12-21 21:16:18 -06:00
subscribeToSeeds();
2024-12-22 09:13:44 -06:00
await new Promise((resolve) => setTimeout(resolve, 500));
askAllPeersForDeltas();
await new Promise((resolve) => setTimeout(resolve, 1000));
2024-12-21 21:16:18 -06:00
2024-12-23 17:29:38 -06:00
users.onUpdate((u: Entity) => {
2024-12-22 09:13:44 -06:00
console.log('User updated:', u);
});
2024-12-23 17:29:38 -06:00
users.onCreate((u: Entity) => {
2024-12-22 09:13:44 -06:00
console.log('New user!:', u);
2024-12-21 21:16:18 -06:00
});
2024-12-23 17:29:38 -06:00
const taliesin = users.put(undefined, {
// id: 'taliesin-1',
name: 'Taliesin',
nameLong: 'Taliesin (Ladd)',
age: Math.floor(Math.random() * 1000)
});
2024-12-21 21:16:18 -06:00
// TODO: Allow configuration regarding read/write concern i.e.
// if we perform a read immediately do we see the value we wrote?
// Intuition says yes, we want that-- but how do we expose the propagation status?
2024-12-23 17:29:38 -06:00
const result = users.get(taliesin.id);
2024-12-21 21:16:18 -06:00
const matches: boolean = JSON.stringify(result) === JSON.stringify(taliesin);
2024-12-22 14:38:01 -06:00
if (matches) {
console.log('Result matches expected: ' + JSON.stringify(taliesin));
} else {
console.log(`Result does not match expected.` +
`\n\nExpected \n${JSON.stringify(taliesin)}` +
`\nReceived\n${JSON.stringify(result)}`);
}
2024-12-21 21:16:18 -06:00
})();