@livequery/mongodb 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,238 @@
1
+ import { Cursor } from './Cursor.js';
2
+ import { MongoQuery } from "./MongoQuery.js";
3
+ import { ObjectId } from 'bson';
4
+ import { SmartCache } from './SmartCache.js';
5
+ import { Subject } from 'rxjs';
6
+ export class MongoDatasource extends Subject {
7
+ #collections = new SmartCache();
8
+ refs = new Map();
9
+ config;
10
+ routes;
11
+ constructor(config) {
12
+ super();
13
+ if (config)
14
+ this.config = config;
15
+ this.routes = new Map();
16
+ }
17
+ async init(configOrRoutes, maybeRoutes) {
18
+ const routes = Array.isArray(configOrRoutes)
19
+ ? configOrRoutes
20
+ : maybeRoutes || [];
21
+ if (!Array.isArray(configOrRoutes)) {
22
+ this.config = configOrRoutes;
23
+ }
24
+ this.routes = routes.reduce((p, c) => {
25
+ const options = this.#getRouteOptions(c);
26
+ if (!options.collection)
27
+ return p;
28
+ const key = this.#routeKey(c.method, c.path);
29
+ const set = p.get(key) || p.get(c.path);
30
+ if (set && set.collection != options.collection)
31
+ throw new Error('Collection mismatch for route path "' + c.path + '"');
32
+ p.set(key, options);
33
+ p.set(c.path, options);
34
+ return p;
35
+ }, new Map());
36
+ }
37
+ async handle(ctx) {
38
+ const request = this.#toLivequeryRequest(ctx);
39
+ if (!request)
40
+ throw { status: 400, code: 'INVALID_LIVEQUERY_REQUEST', message: 'Invalid livequery request' };
41
+ const options = this.#getOptions(ctx);
42
+ ctx.response = await this.query(request, options);
43
+ return ctx.response;
44
+ }
45
+ async query(req, options) {
46
+ if (!this.config)
47
+ throw { status: 500, code: 'DB_CONFIG_NOT_FOUND', message: 'Database config not found' };
48
+ const collection = await this.#getCollection(req, options);
49
+ const query = this.#normalizeObjectIds(this.#normalizeRequest(req), options.objectIdFields || []);
50
+ if (query.method == 'get')
51
+ return await this.#get(query, collection);
52
+ if (query.method == 'post')
53
+ return this.#post(query, collection);
54
+ if (query.method == 'put')
55
+ return this.#put(query, collection);
56
+ if (query.method == 'patch')
57
+ return this.#patch(query, collection);
58
+ if (query.method == 'delete')
59
+ return this.#del(query, collection);
60
+ throw { status: 500, code: 'INVAILD_METHOD', message: 'Invaild method' };
61
+ }
62
+ #getRouteOptions(route) {
63
+ const legacy = route;
64
+ if (legacy.options)
65
+ return legacy.options;
66
+ if (legacy.config)
67
+ return legacy.config;
68
+ const { method, path, ...options } = route;
69
+ return options;
70
+ }
71
+ #getOptions(ctx) {
72
+ const routePath = ctx.request.ref || ctx.request.path;
73
+ const options = this.routes.get(this.#routeKey(ctx.request.method, routePath)) || this.routes.get(routePath);
74
+ if (!options)
75
+ throw { status: 404, code: 'ROUTE_OPTIONS_NOT_FOUND', message: `Route options for "${routePath}" not found` };
76
+ return options;
77
+ }
78
+ #routeKey(method, path) {
79
+ return `${String(method).toUpperCase()} ${path}`;
80
+ }
81
+ #toLivequeryRequest(ctx) {
82
+ const livequery = ctx.livequery;
83
+ if (!livequery)
84
+ return undefined;
85
+ return {
86
+ ref: livequery.ref,
87
+ is_collection: !livequery.document_id,
88
+ collection_ref: livequery.collection_ref,
89
+ schema_collection_ref: livequery.schema_collection_ref,
90
+ doc_id: livequery.document_id,
91
+ keys: livequery.keys || {},
92
+ query: livequery.query || {},
93
+ options: livequery.query || {},
94
+ method: livequery.method?.toLowerCase(),
95
+ body: livequery.body,
96
+ };
97
+ }
98
+ #normalizeRequest(req) {
99
+ const options = req.options || req.query || {};
100
+ return {
101
+ ...req,
102
+ keys: req.keys || {},
103
+ query: req.query || options,
104
+ options,
105
+ is_collection: typeof req.is_collection == 'boolean' ? req.is_collection : !req.document_id,
106
+ doc_id: req.doc_id || req.document_id,
107
+ method: req.method?.toLowerCase(),
108
+ };
109
+ }
110
+ async #getCollection(req, options) {
111
+ const connectionName = typeof options.connection == 'function' ? await options.connection(req) : (options.connection || Object.keys(this.config.connections)[0] || 'default');
112
+ const dbName = typeof options.db == 'function' ? await options.db(req) : (options.db || process.env.DB_NAME || 'main');
113
+ const collectionName = typeof options.collection == 'function' ? await options.collection(req) : options.collection;
114
+ return await this.#collections.get(`${connectionName}|${dbName}|${collectionName}`, async () => {
115
+ const connection = this.config.connections[connectionName];
116
+ if (!connection)
117
+ throw { status: 500, code: 'DB_CONNECTION_NOT_FOUND', message: `Database connection "${connectionName}" not found` };
118
+ const db = this.#isDb(connection) ? connection : connection.db(dbName);
119
+ return db.collection(collectionName);
120
+ });
121
+ }
122
+ #isDb(connection) {
123
+ return typeof connection.collection == 'function';
124
+ }
125
+ async #get(req, collection) {
126
+ const { limit, items, count, has, summary } = await MongoQuery.query(req, collection);
127
+ const current = items.length;
128
+ const total = current + count.next + count.prev;
129
+ const paging = {
130
+ cursor: {
131
+ last: Cursor.caculate(items[items.length - 1], req.options),
132
+ first: Cursor.caculate(items[0], req.options)
133
+ },
134
+ has,
135
+ count: {
136
+ ...count,
137
+ current,
138
+ total
139
+ },
140
+ page: {
141
+ current: Math.floor(count.prev / limit + 1),
142
+ total: Math.ceil(total / limit)
143
+ }
144
+ };
145
+ if (req.is_collection) {
146
+ const data = {
147
+ ...paging,
148
+ items,
149
+ summary,
150
+ };
151
+ return data;
152
+ }
153
+ const item = items[0];
154
+ return {
155
+ summary,
156
+ ...paging,
157
+ "has": {
158
+ "prev": false,
159
+ "next": false
160
+ },
161
+ "count": {
162
+ "prev": 0,
163
+ "next": 0,
164
+ "current": item ? 1 : 0,
165
+ "total": item ? 1 : 0
166
+ },
167
+ "page": {
168
+ "current": item ? 1 : 0,
169
+ "total": item ? 1 : 0
170
+ },
171
+ item,
172
+ };
173
+ }
174
+ async #post(req, collection) {
175
+ const merged = {
176
+ ...req.keys,
177
+ ...req.body
178
+ };
179
+ const result = await collection.insertOne(merged);
180
+ return {
181
+ item: {
182
+ ...merged,
183
+ _id: undefined,
184
+ id: result.insertedId.toString()
185
+ }
186
+ };
187
+ }
188
+ async #put(req, collection) {
189
+ return await collection.updateOne(this.#keys(req), this.#update(req.body));
190
+ }
191
+ async #patch(req, collection) {
192
+ return await collection.updateOne(this.#keys(req), this.#update(req.body));
193
+ }
194
+ async #del(req, collection) {
195
+ return await collection.deleteOne(this.#keys(req));
196
+ }
197
+ #keys(req) {
198
+ return Object.entries(req.keys).reduce((p, [k, c]) => {
199
+ return {
200
+ ...p,
201
+ ...k == 'id' ? {
202
+ _id: ObjectId.createFromHexString(req.keys.id)
203
+ } : {
204
+ [k]: c
205
+ }
206
+ };
207
+ }, {});
208
+ }
209
+ #update(body) {
210
+ if (!body || Object.keys(body).some(key => key.startsWith('$')))
211
+ return body;
212
+ return { $set: body };
213
+ }
214
+ #convert(obj, fields) {
215
+ return {
216
+ ...obj,
217
+ ...[...fields].reduce((p, c) => {
218
+ if (obj[c] && typeof obj[c] == 'string' && ObjectId.isValid(obj[c])) {
219
+ return {
220
+ ...p,
221
+ [c]: ObjectId.createFromHexString(obj[c])
222
+ };
223
+ }
224
+ return p;
225
+ }, {})
226
+ };
227
+ }
228
+ #normalizeObjectIds(req, fields) {
229
+ const objectIdFields = new Set(fields);
230
+ if (objectIdFields.size == 0)
231
+ return req;
232
+ return {
233
+ ...req,
234
+ ...req.keys ? { keys: this.#convert(req.keys, objectIdFields) } : {},
235
+ ...req.body ? { body: this.#convert(req.body, objectIdFields) } : {}
236
+ };
237
+ }
238
+ }
@@ -0,0 +1,18 @@
1
+ import type { LivequeryBaseEntity, LivequeryRequest } from "./types.js";
2
+ import type { Collection } from "mongodb";
3
+ export declare class MongoQuery {
4
+ #private;
5
+ static query<T extends LivequeryBaseEntity>(req: LivequeryRequest<T>, collection: Collection<T>): Promise<{
6
+ limit: number;
7
+ summary: any;
8
+ items: T[];
9
+ has: {
10
+ next: boolean;
11
+ prev: boolean;
12
+ };
13
+ count: {
14
+ next: number;
15
+ prev: number;
16
+ };
17
+ }>;
18
+ }