Readme

Silly mongo-like client on Val Town SQLite inspired by Pongo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { sqlite } from "https://esm.town/v/std/sqlite?v=4";
import { v4 as uuid } from "npm:uuid";
class MongoDB<T extends object> {
async connect() {
await sqlite.execute(`CREATE TABLE IF NOT EXISTS MongoDB (_id TEXT PRIMARY KEY, data TEXT)`);
}
async insertOne(data: T) {
const _id = uuid();
await sqlite.execute({
sql: "INSERT INTO MongoDB (_id, data) VALUES (?, ?)",
args: [_id, JSON.stringify(data)],
});
return { insertedId: _id };
}
async updateOne(query: { _id: string }, update: { $set: Partial<T> }) {
const result = await sqlite.execute({
sql: "SELECT data FROM MongoDB WHERE _id = ?",
args: [query._id],
});
if (!result.rows.length) return false;
const newData = { ...JSON.parse(result.rows[0][0] as string), ...update.$set };
await sqlite.execute({
sql: "UPDATE MongoDB SET data = ? WHERE _id = ?",
args: [JSON.stringify(newData), query._id],
});
return true;
}
async findOne(query: { _id: string }): Promise<T | null> {
const result = await sqlite.execute({
sql: "SELECT data FROM MongoDB WHERE _id = ?",
args: [query._id],
});
return result.rows.length ? JSON.parse(result.rows[0][0] as string) : null;
}
}
// Example usage
type User = { name: string; age: number };
const mongodb = new MongoDB<User>();
// Ensure the table is setup
await mongodb.connect();
const anita: User = { name: "Anita", age: 25 };
const { insertedId: anitaId } = await mongodb.insertOne(anita);
await mongodb.insertOne(anita);
// updating by id
await mongodb.updateOne({ _id: anitaId }, { $set: { age: 31 } });
// finding by id
const anitaUpdated = await mongodb.findOne({ _id: anitaId });
console.log(anitaUpdated);
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
July 8, 2024