@sfxcode/mongocamp-server-core 2.3.0 → 2.5.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.
- package/dist/index.d.mts +568 -169
- package/dist/index.mjs +3147 -2225
- package/package.json +8 -2
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { MongoClient, Db, Collection, Document as Document$2 } from 'mongodb';
|
|
1
|
+
import { MongoClient, Db, Collection, Document as Document$2, ObjectId } from 'mongodb';
|
|
2
2
|
import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
3
3
|
export { StandardSchemaV1 } from '@standard-schema/spec';
|
|
4
4
|
import * as hookable from 'hookable';
|
|
@@ -23,6 +23,7 @@ declare const ConfigKeys: {
|
|
|
23
23
|
readonly ServerInterface: "SERVER_INTERFACE";
|
|
24
24
|
readonly ServerPort: "SERVER_PORT";
|
|
25
25
|
readonly AggregationStagesDenied: "AGGREGATION_STAGES_DENIED";
|
|
26
|
+
readonly FilterOperatorsDenied: "FILTER_OPERATORS_DENIED";
|
|
26
27
|
readonly AuthHandler: "AUTH_HANDLER";
|
|
27
28
|
readonly AuthSecret: "AUTH_SECRET";
|
|
28
29
|
readonly AuthApiKeyLength: "AUTH_APIKEYLENGTH";
|
|
@@ -32,6 +33,14 @@ declare const ConfigKeys: {
|
|
|
32
33
|
readonly AuthGrantDeniedStatus: "AUTH_GRANT_DENIED_STATUS";
|
|
33
34
|
readonly ImportMaxBytes: "IMPORT_MAX_BYTES";
|
|
34
35
|
readonly WatchMaxStreams: "WATCH_MAX_STREAMS";
|
|
36
|
+
readonly BodyMaxBytes: "BODY_MAX_BYTES";
|
|
37
|
+
readonly PagingMaxRows: "PAGING_MAX_ROWS";
|
|
38
|
+
readonly ExportMaxDocuments: "EXPORT_MAX_DOCUMENTS";
|
|
39
|
+
readonly GridfsUploadMaxBytes: "GRIDFS_UPLOAD_MAX_BYTES";
|
|
40
|
+
readonly WatchQueueMax: "WATCH_QUEUE_MAX";
|
|
41
|
+
readonly ServerHeaderEnabled: "SERVER_HEADER_ENABLED";
|
|
42
|
+
readonly ErrorsExposeInternal: "ERRORS_EXPOSE_INTERNAL";
|
|
43
|
+
readonly ExportCsvEscapeFormulas: "EXPORT_CSV_ESCAPE_FORMULAS";
|
|
35
44
|
readonly FilterTimeZone: "FILTER_TIME_ZONE";
|
|
36
45
|
readonly MigrationDropScalaLeftovers: "MIGRATION_DROP_SCALA_LEFTOVERS";
|
|
37
46
|
readonly JobsEnabled: "JOBS_ENABLED";
|
|
@@ -81,9 +90,9 @@ declare class ConfigurationError extends Error {
|
|
|
81
90
|
type ConfigEnv = Record<string, string | undefined>;
|
|
82
91
|
interface ConfigSources {
|
|
83
92
|
/** Environment variables, `process.env` when omitted. */
|
|
84
|
-
env?: ConfigEnv;
|
|
93
|
+
env?: ConfigEnv | undefined;
|
|
85
94
|
/** Programmatic values (e.g. from Nuxt runtimeConfig). Strings are parsed like env values, other values are taken as they are. */
|
|
86
|
-
values?: Partial<Record<ConfigKey, unknown
|
|
95
|
+
values?: Partial<Record<ConfigKey, unknown>> | undefined;
|
|
87
96
|
}
|
|
88
97
|
/**
|
|
89
98
|
* In-memory view of all configurations. Precedence: definition default < programmatic values < env.
|
|
@@ -183,6 +192,19 @@ declare class MongocampError extends Error {
|
|
|
183
192
|
/** A request that cannot be decoded (`MongoCampDefaultDecodeFailureHandler`): `what` names the input, e.g. `body` or `query parameter page`. */
|
|
184
193
|
static decodeFailure(what: string, additionalInfo?: string): MongocampError;
|
|
185
194
|
}
|
|
195
|
+
type ErrorLogger = (error: unknown, status: number) => void;
|
|
196
|
+
interface ErrorResponseOptions {
|
|
197
|
+
/** The message of an unexpected error in the answer (`ERRORS_EXPOSE_INTERNAL`, for development); by default only the log has it. */
|
|
198
|
+
exposeInternal?: boolean | undefined;
|
|
199
|
+
}
|
|
200
|
+
/** The message of an unexpected error (2.5.0): its text stays in the log, the client gets the request id (header `x-request-id`). */
|
|
201
|
+
declare const InternalErrorMessage = "internal server error, the log of the server has the details (x-request-id)";
|
|
202
|
+
/**
|
|
203
|
+
* Maps anything thrown in a handler to the error response of the Scala server (`MongoCampExceptionHandler`): a `MongocampError` as it is,
|
|
204
|
+
* a database error with the status for its code and a message without internal names, everything else as 500 with code -1 and a generic
|
|
205
|
+
* message (2.5.0; before, the message of the error, which can name internals).
|
|
206
|
+
*/
|
|
207
|
+
declare function toErrorResponse(error: unknown, log?: ErrorLogger, options?: ErrorResponseOptions): Response;
|
|
186
208
|
|
|
187
209
|
/** Pagination of list routes (`PagingFunctions.scala`, `MongoPaginatedFilter.scala`): 1-based pages, 100 rows per page by default. */
|
|
188
210
|
declare const DefaultRowsPerPage = 100;
|
|
@@ -195,10 +217,12 @@ declare const PaginationHeaders: {
|
|
|
195
217
|
};
|
|
196
218
|
/** `after` switches to cursor paging (`http/cursor.ts`): the token of the previous page, or empty for the first page. */
|
|
197
219
|
interface Paging {
|
|
198
|
-
rowsPerPage?: number;
|
|
199
|
-
page?: number;
|
|
200
|
-
after?: string;
|
|
220
|
+
rowsPerPage?: number | undefined;
|
|
221
|
+
page?: number | undefined;
|
|
222
|
+
after?: string | undefined;
|
|
201
223
|
}
|
|
224
|
+
/** Query parameter `count`: `exact` (default) counts the matching documents, `none` skips the count and its headers. */
|
|
225
|
+
type CountMode = 'exact' | 'none';
|
|
202
226
|
/**
|
|
203
227
|
* `allCount` and `pagesCount` are missing when the count was skipped (`count=none`), `page` with cursor paging; `next` is the cursor of the
|
|
204
228
|
* next page, missing when the page is the last one.
|
|
@@ -380,7 +404,6 @@ interface LoginResult {
|
|
|
380
404
|
expirationDate: string;
|
|
381
405
|
}
|
|
382
406
|
declare class AuthService {
|
|
383
|
-
private readonly database;
|
|
384
407
|
private readonly config;
|
|
385
408
|
private readonly version;
|
|
386
409
|
readonly holder: AuthHolder;
|
|
@@ -400,6 +423,8 @@ declare class AuthService {
|
|
|
400
423
|
*/
|
|
401
424
|
authenticateUser(credentials: Credentials): Promise<UserInformation>;
|
|
402
425
|
/** The logged in user of a request with the current roles. */
|
|
426
|
+
/** A user by id with its roles (2.4.0, the server collection acting for a user); 401 for a user that does not exist. */
|
|
427
|
+
authorizedUser(userId: string): Promise<AuthorizedUser>;
|
|
403
428
|
authenticate(request: Request): Promise<AuthorizedUser>;
|
|
404
429
|
/** The id of the user a request was authenticated as, `undefined` before (or without) the authentication. */
|
|
405
430
|
userOf(request: Request): string | undefined;
|
|
@@ -407,6 +432,8 @@ declare class AuthService {
|
|
|
407
432
|
grantDenied(message: string): MongocampError;
|
|
408
433
|
requireAdmin(request: Request): Promise<AuthorizedUser>;
|
|
409
434
|
requireCollection(request: Request, collection: string, right: 'read' | 'write' | 'administrate'): Promise<AuthorizedUser>;
|
|
435
|
+
/** The grant of an authenticated user for a collection (the routes and the document service, 2.4.0). */
|
|
436
|
+
requireRight(user: AuthorizedUser, collection: string, right: 'read' | 'write' | 'administrate'): void;
|
|
410
437
|
requireBucket(request: Request, bucket: string, right: 'read' | 'write' | 'administrate'): Promise<AuthorizedUser>;
|
|
411
438
|
profileOf(user: UserInformation): Promise<UserProfile>;
|
|
412
439
|
/** A new token for the user (`AuthHolder.generateLoginResult`), valid for `AUTH_EXPIRING_DURATION`. */
|
|
@@ -436,7 +463,7 @@ declare function requestLogging(): MongocampFeature;
|
|
|
436
463
|
declare function metrics(): MongocampFeature;
|
|
437
464
|
|
|
438
465
|
/**
|
|
439
|
-
* Behaviours of declared collections (2.
|
|
466
|
+
* Behaviours of declared collections (2.3.0): one flag each in `defineMongocampCollection`, with working defaults; an options object
|
|
440
467
|
* renames the fields (dot paths for nested fields, e.g. `metaData.created`).
|
|
441
468
|
*
|
|
442
469
|
* defineMongocampCollection({ name: 'orders', schema, timestamps: true, owner: true, softDelete: true, versioned: true, audit: true })
|
|
@@ -574,6 +601,139 @@ type DeepPartial<T> = T extends Date | readonly unknown[] ? T : T extends object
|
|
|
574
601
|
[K in keyof T]?: DeepPartial<T[K]>;
|
|
575
602
|
} : T;
|
|
576
603
|
|
|
604
|
+
/**
|
|
605
|
+
* The indexes of a declared collection at the start (2.4.0). The sync only manages its **own** indexes (names `mongocamp_idx_*`):
|
|
606
|
+
*
|
|
607
|
+
* - a missing one is created (all missing ones in one `createIndexes`);
|
|
608
|
+
* - one whose key or options changed is dropped and created again — MongoDB cannot change most index options; only the seconds of a TTL
|
|
609
|
+
* index are changed in place (`collMod`);
|
|
610
|
+
* - an own index that is no longer declared is dropped;
|
|
611
|
+
* - an index of someone else (made by hand, by another tool, `_id_`) is never touched, only reported;
|
|
612
|
+
* - a failure (e.g. duplicate values for a unique index) is logged; the start goes on, the other indexes are synced.
|
|
613
|
+
*
|
|
614
|
+
* Every instance runs it; the second one changes nothing.
|
|
615
|
+
*/
|
|
616
|
+
interface IndexSyncResult {
|
|
617
|
+
collection: string;
|
|
618
|
+
created: string[];
|
|
619
|
+
replaced: string[];
|
|
620
|
+
dropped: string[];
|
|
621
|
+
unchanged: string[];
|
|
622
|
+
/** Indexes that are not own ones (left alone). */
|
|
623
|
+
foreign: string[];
|
|
624
|
+
/** Indexes that could not be created or changed, with the reason. */
|
|
625
|
+
failed: Array<{
|
|
626
|
+
name: string;
|
|
627
|
+
reason: string;
|
|
628
|
+
}>;
|
|
629
|
+
}
|
|
630
|
+
/** Syncs the indexes of one declared collection; never throws (an unexpected failure is reported in `failed`). */
|
|
631
|
+
declare function syncIndexes(db: Db, declared: DeclaredCollection, logger: MongocampLogger): Promise<IndexSyncResult>;
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* Indexes of declared collections (2.4.0): the shortest form that says what is needed, the indexes the behaviours need added by
|
|
635
|
+
* themselves. The sync at the start (`index-sync.ts`) creates them; it only manages its own indexes (names `mongocamp_idx_*`).
|
|
636
|
+
*
|
|
637
|
+
* indexes: [
|
|
638
|
+
* 'status', // { status: 1 }
|
|
639
|
+
* '-createdAt', // { createdAt: -1 }
|
|
640
|
+
* ['customerId', '-createdAt'], // compound
|
|
641
|
+
* { fields: { number: 1 }, unique: true }, // with options
|
|
642
|
+
* { fields: { text: 'text' } }, // text index
|
|
643
|
+
* { fields: { expiresAt: 1 }, expireAfterSeconds: 0 }, // TTL
|
|
644
|
+
* ]
|
|
645
|
+
*/
|
|
646
|
+
type IndexDirection = 1 | -1 | 'text';
|
|
647
|
+
interface IndexOptions {
|
|
648
|
+
fields: Record<string, IndexDirection>;
|
|
649
|
+
unique?: boolean;
|
|
650
|
+
sparse?: boolean;
|
|
651
|
+
/** TTL: documents expire this many seconds after the date in the (single) field. */
|
|
652
|
+
expireAfterSeconds?: number;
|
|
653
|
+
partialFilterExpression?: Document$2;
|
|
654
|
+
collation?: Document$2;
|
|
655
|
+
/** A name of your own (prefixed with `mongocamp_idx_`); default made of the fields. */
|
|
656
|
+
name?: string;
|
|
657
|
+
}
|
|
658
|
+
/** A field (`'status'`, `'-createdAt'`), fields of a compound index, or an index with options. */
|
|
659
|
+
type IndexDeclaration = string | readonly string[] | IndexOptions;
|
|
660
|
+
declare const OwnIndexPrefix = "mongocamp_idx_";
|
|
661
|
+
interface ResolvedIndex {
|
|
662
|
+
name: string;
|
|
663
|
+
key: Record<string, IndexDirection>;
|
|
664
|
+
options: Document$2;
|
|
665
|
+
/** Key and options, to see whether a stored index is still the declared one. */
|
|
666
|
+
fingerprint: string;
|
|
667
|
+
/** Declared, or added for a behaviour. */
|
|
668
|
+
origin: 'declaration' | 'owner';
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* The indexes of a declaration: the declared ones and the ones of its behaviours (an index on the owner field; with soft delete, unique
|
|
672
|
+
* indexes count only documents that are not deleted, so a deleted value can be used again).
|
|
673
|
+
*/
|
|
674
|
+
declare function resolveIndexes(declarations: readonly IndexDeclaration[] | undefined, behaviours: ResolvedBehaviours): ResolvedIndex[];
|
|
675
|
+
|
|
676
|
+
/**
|
|
677
|
+
* References of declared collections (2.4.0): which fields hold the `_id` of a document of another collection. A read with
|
|
678
|
+
* `expand=customerId` replaces the id by the document — read with the grants and the scope of the target, never more than a direct read.
|
|
679
|
+
*
|
|
680
|
+
* refs: {
|
|
681
|
+
* customerId: 'customers', // one id
|
|
682
|
+
* tagIds: 'tags', // an array of ids (from the schema, or the value)
|
|
683
|
+
* 'billing.accountId': 'crm:accounts', // a nested field, a collection of another database
|
|
684
|
+
* }
|
|
685
|
+
*/
|
|
686
|
+
/** The target collection (`name` or `database:name`), or an object with it. */
|
|
687
|
+
type RefDeclaration = string | {
|
|
688
|
+
readonly collection: string;
|
|
689
|
+
};
|
|
690
|
+
interface ResolvedRef {
|
|
691
|
+
/** The field path of the reference. */
|
|
692
|
+
field: string;
|
|
693
|
+
/** The target collection as the API names it (`name` or `database:name`). */
|
|
694
|
+
collection: string;
|
|
695
|
+
/** An array of ids (from the schema); `undefined` when the schema does not tell, then the value decides. */
|
|
696
|
+
many?: boolean;
|
|
697
|
+
}
|
|
698
|
+
/** At most this many references are expanded by one read. */
|
|
699
|
+
declare const MaxExpands = 5;
|
|
700
|
+
/**
|
|
701
|
+
* The references of a declaration. `jsonSchema` is the schema of the documents (MongoDB form) when the schema has one: it tells which
|
|
702
|
+
* references are arrays. Refused: `_id`, a field a behaviour writes, a path through an array, an empty or invalid target.
|
|
703
|
+
*/
|
|
704
|
+
declare function resolveRefs(refs: Readonly<Record<string, RefDeclaration>> | undefined, behaviours: ResolvedBehaviours, jsonSchema?: Document$2): ResolvedRef[];
|
|
705
|
+
/** The target collection names of a refs declaration: `{ customerId: 'customers' }`. */
|
|
706
|
+
type RefTargets<R> = {
|
|
707
|
+
-readonly [K in keyof R]: R[K] extends string ? R[K] : R[K] extends {
|
|
708
|
+
collection: infer C extends string;
|
|
709
|
+
} ? C : never;
|
|
710
|
+
};
|
|
711
|
+
/** The refs of a declaration as field → target collection name (`{}` without refs). */
|
|
712
|
+
type InferRefs<D> = D extends {
|
|
713
|
+
refs: infer R;
|
|
714
|
+
} ? RefTargets<R> : Record<never, never>;
|
|
715
|
+
type Simplify<T> = {
|
|
716
|
+
[K in keyof T]: T[K];
|
|
717
|
+
} & {};
|
|
718
|
+
/** The value an expanded reference becomes: the target document or `null`; an array of ids becomes an array of documents. */
|
|
719
|
+
type ExpandedValue<V, Target> = NonNullable<V> extends readonly unknown[] ? Target[] : Target | null;
|
|
720
|
+
/** `T` with the value at the dot path `P` expanded to `Target` (optional fields stay optional). */
|
|
721
|
+
type ExpandAt<T, P extends string, Target> = P extends `${infer Head}.${infer Rest}` ? Head extends keyof T ? {
|
|
722
|
+
[K in keyof T]: K extends Head ? ExpandAt<NonNullable<T[K]>, Rest, Target> | Extract<T[K], null | undefined> : T[K];
|
|
723
|
+
} : T : P extends keyof T ? {
|
|
724
|
+
[K in keyof T]: K extends P ? ExpandedValue<T[K], Target> : T[K];
|
|
725
|
+
} : Simplify<T & {
|
|
726
|
+
[K in P]?: Target | Target[] | null;
|
|
727
|
+
}>;
|
|
728
|
+
type ExpandAll<T, Refs, Keys, Collections> = Keys extends readonly [infer First extends string, ...infer Rest] ? ExpandAll<ExpandAt<T, First, First extends keyof Refs ? (Refs[First] extends keyof Collections ? Collections[Refs[First]] : Record<string, unknown>) : Record<string, unknown>>, Refs, Rest, Collections> : T;
|
|
729
|
+
type UnionToTuple<U, Last = LastOf<U>> = [U] extends [never] ? [] : [...UnionToTuple<Exclude<U, Last>>, Last];
|
|
730
|
+
type LastOf<U> = ((U extends unknown ? (value: () => U) => void : never) extends (value: infer I) => void ? I : never) extends () => infer L ? L : never;
|
|
731
|
+
/**
|
|
732
|
+
* A document with the references `K` expanded: `ExpandedDocument<Order, { customerId: 'customers' }, 'customerId', { customers: Customer }>`
|
|
733
|
+
* has `customerId: Customer | null`. A target without a known type is `Record<string, unknown>`.
|
|
734
|
+
*/
|
|
735
|
+
type ExpandedDocument<T, Refs, K extends keyof Refs & string, Collections = Record<never, never>> = ExpandAll<T, Refs, UnionToTuple<K>, Collections>;
|
|
736
|
+
|
|
577
737
|
/**
|
|
578
738
|
* The validator of MongoDB for the declared collections (2.3.0), set when the declarations are registered. The validator of a declared
|
|
579
739
|
* collection belongs to its declaration:
|
|
@@ -618,7 +778,7 @@ declare function syncValidator(db: Db, declared: DeclaredCollection, logger: Mon
|
|
|
618
778
|
type ValidationMode = 'off' | 'warn' | 'error';
|
|
619
779
|
declare const DefaultValidationMode: ValidationMode;
|
|
620
780
|
/**
|
|
621
|
-
* A declared collection. Behaviours (2.
|
|
781
|
+
* A declared collection. Behaviours (2.3.0) are flags of the same object: `timestamps`, `owner`, `softDelete`, `versioned`, `audit`,
|
|
622
782
|
* `protectedFields` (see `BehaviourFlags`).
|
|
623
783
|
*/
|
|
624
784
|
interface MongocampCollectionDefinition<S extends StandardSchemaV1 = StandardSchemaV1> extends BehaviourFlags {
|
|
@@ -631,7 +791,11 @@ interface MongocampCollectionDefinition<S extends StandardSchemaV1 = StandardSch
|
|
|
631
791
|
/** Default `warn`. */
|
|
632
792
|
validation?: ValidationMode;
|
|
633
793
|
/** A `$jsonSchema` validator for MongoDB that replaces the one converted from the schema (for schemas without JSON Schema form). */
|
|
634
|
-
validator?: Document$2;
|
|
794
|
+
validator?: Document$2 | undefined;
|
|
795
|
+
/** Indexes (2.4.0): `'status'`, `'-createdAt'`, `['a', '-b']` or `{ fields, unique, ... }`; synced at the start (own indexes only). */
|
|
796
|
+
indexes?: readonly IndexDeclaration[];
|
|
797
|
+
/** References (2.4.0): field → target collection (`'customers'`, `'db:customers'`), for `expand` on reads. */
|
|
798
|
+
refs?: Readonly<Record<string, RefDeclaration>>;
|
|
635
799
|
/** Where the declaration comes from (a file), for the messages; set by the Nuxt module. */
|
|
636
800
|
source?: string;
|
|
637
801
|
}
|
|
@@ -644,13 +808,20 @@ type InferDocument<D extends MongocampCollectionDefinition> = unknown extends Sy
|
|
|
644
808
|
type InferDocumentInput<D extends MongocampCollectionDefinition> = unknown extends SystemFields<D> ? StandardSchemaV1.InferInput<D['schema']> : Merge<StandardSchemaV1.InferInput<D['schema']> & DeepPartial<SystemFields<D>>>;
|
|
645
809
|
/** Declares a collection; checks the declaration and keeps the types of its schema and its behaviours for `InferDocument`. */
|
|
646
810
|
declare function defineMongocampCollection<const D extends MongocampCollectionDefinition>(definition: D): D;
|
|
647
|
-
/**
|
|
811
|
+
/** The resolved references of a declaration; errors name the collection and the source. */
|
|
812
|
+
declare function refsOf(definition: MongocampCollectionDefinition, behaviours?: ResolvedBehaviours): ResolvedRef[];
|
|
648
813
|
interface DeclaredCollection {
|
|
649
814
|
definition: MongocampCollectionDefinition;
|
|
650
815
|
databaseName: string;
|
|
651
816
|
validation: ValidationMode;
|
|
652
|
-
/** The behaviours of the declaration with their defaults (2.
|
|
817
|
+
/** The behaviours of the declaration with their defaults (2.3.0). */
|
|
653
818
|
behaviours: ResolvedBehaviours;
|
|
819
|
+
/** The indexes of the declaration and its behaviours (2.4.0); empty when there are none. */
|
|
820
|
+
indexes: ResolvedIndex[];
|
|
821
|
+
/** The references of the declaration (2.4.0); empty when there are none. */
|
|
822
|
+
refs: ResolvedRef[];
|
|
823
|
+
/** What the start did with the indexes (2.4.0). */
|
|
824
|
+
indexSync?: IndexSyncResult;
|
|
654
825
|
/** What the start did with the validator of MongoDB (`collections()` feature). */
|
|
655
826
|
sync?: ValidatorSyncResult;
|
|
656
827
|
}
|
|
@@ -855,7 +1026,7 @@ interface components {
|
|
|
855
1026
|
additionalInfo: string;
|
|
856
1027
|
/** @description The fields of a document that is not valid (a schema, a before-hook or the validator of the collection). Only set for these errors. */
|
|
857
1028
|
issues?: components["schemas"]["ValidationIssue"][];
|
|
858
|
-
/** @description The stored document of a version conflict (409, code 4092, 2.
|
|
1029
|
+
/** @description The stored document of a version conflict (409, code 4092, 2.3.0), as Extended JSON: show it or merge with it, then send the change again with its version. */
|
|
859
1030
|
current?: {
|
|
860
1031
|
[key: string]: unknown;
|
|
861
1032
|
};
|
|
@@ -1097,6 +1268,8 @@ interface components {
|
|
|
1097
1268
|
filter: components["schemas"]["Map_Any"];
|
|
1098
1269
|
sort: components["schemas"]["Map_Any"];
|
|
1099
1270
|
projection: components["schemas"]["Map_Any"];
|
|
1271
|
+
/** @description References to expand (2.4.0), like the query parameter expand. */
|
|
1272
|
+
expand?: string[];
|
|
1100
1273
|
};
|
|
1101
1274
|
/** MongoIndex */
|
|
1102
1275
|
MongoIndex: {
|
|
@@ -1218,6 +1391,22 @@ interface components {
|
|
|
1218
1391
|
/** @description The fields the server writes (timestamps, owner, version, deleted mark); clients do not send them. */
|
|
1219
1392
|
systemFields: string[];
|
|
1220
1393
|
protectedFields: string[];
|
|
1394
|
+
/** @description The indexes of the declaration and its behaviours (2.4.0), synced at the start. */
|
|
1395
|
+
indexes: {
|
|
1396
|
+
name: string;
|
|
1397
|
+
key: {
|
|
1398
|
+
[key: string]: unknown;
|
|
1399
|
+
};
|
|
1400
|
+
unique: boolean;
|
|
1401
|
+
}[];
|
|
1402
|
+
/** @description The references of the declaration (2.4.0), the fields a read can expand (query parameter expand). */
|
|
1403
|
+
refs: {
|
|
1404
|
+
field: string;
|
|
1405
|
+
/** @description The target collection (name or database:name). */
|
|
1406
|
+
collection: string;
|
|
1407
|
+
/** @description Whether the field holds an array of ids (from the schema); missing when the schema does not tell. */
|
|
1408
|
+
many?: boolean;
|
|
1409
|
+
}[];
|
|
1221
1410
|
timestamps?: {
|
|
1222
1411
|
createdAt: string;
|
|
1223
1412
|
updatedAt: string;
|
|
@@ -1280,6 +1469,8 @@ interface components {
|
|
|
1280
1469
|
projection?: string[];
|
|
1281
1470
|
/** Format: int32 */
|
|
1282
1471
|
limit?: number;
|
|
1472
|
+
/** @description References to expand (2.4.0), like the query parameter expand. */
|
|
1473
|
+
expand?: string[];
|
|
1283
1474
|
};
|
|
1284
1475
|
/** CountRequest */
|
|
1285
1476
|
CountRequest: {
|
|
@@ -1291,6 +1482,8 @@ interface components {
|
|
|
1291
1482
|
filter?: string;
|
|
1292
1483
|
sort?: string[];
|
|
1293
1484
|
projection?: string[];
|
|
1485
|
+
/** @description References to expand (2.4.0), like the query parameter expand. */
|
|
1486
|
+
expand?: string[];
|
|
1294
1487
|
};
|
|
1295
1488
|
/** SettingsResponse */
|
|
1296
1489
|
SettingsResponse: {
|
|
@@ -1463,28 +1656,28 @@ interface MongocampEvents {
|
|
|
1463
1656
|
collectionName: string;
|
|
1464
1657
|
newCollectionName: string;
|
|
1465
1658
|
}>;
|
|
1466
|
-
/** `documents` (2.
|
|
1659
|
+
/** `documents` (2.3.0): the inserted documents of an insert or insertMany (not of an import), read only by listeners that need them. */
|
|
1467
1660
|
'document:create': ByUser<{
|
|
1468
1661
|
collectionName: string;
|
|
1469
1662
|
insertResponse: Schemas['InsertResponse'];
|
|
1470
1663
|
documents?: Document$1[];
|
|
1471
1664
|
}>;
|
|
1472
1665
|
/** `oldValues` are read only when a listener is registered for the hook. */
|
|
1473
|
-
/** `source` (2.
|
|
1666
|
+
/** `source` (2.3.0): a replace, a partial update or an update of many documents. */
|
|
1474
1667
|
'document:update': ByUser<{
|
|
1475
1668
|
collectionName: string;
|
|
1476
1669
|
updateResponse: Schemas['UpdateResponse'];
|
|
1477
1670
|
oldValues: Document$1[];
|
|
1478
1671
|
source?: 'replace' | 'update' | 'updateMany';
|
|
1479
1672
|
}>;
|
|
1480
|
-
/** `softDeleted` (2.
|
|
1673
|
+
/** `softDeleted` (2.3.0): a before-hook turned the delete into an update (`instead`), the documents are still stored. */
|
|
1481
1674
|
'document:delete': ByUser<{
|
|
1482
1675
|
collectionName: string;
|
|
1483
1676
|
deleteResponse: Schemas['DeleteResponse'];
|
|
1484
1677
|
oldValues: Document$1[];
|
|
1485
1678
|
softDeleted?: boolean;
|
|
1486
1679
|
}>;
|
|
1487
|
-
/** A soft-deleted document was restored (2.
|
|
1680
|
+
/** A soft-deleted document was restored (2.3.0); `oldValues` as for updates. */
|
|
1488
1681
|
'document:restore': ByUser<{
|
|
1489
1682
|
collectionName: string;
|
|
1490
1683
|
updateResponse: Schemas['UpdateResponse'];
|
|
@@ -1549,13 +1742,13 @@ declare class EventBus {
|
|
|
1549
1742
|
private readonly log;
|
|
1550
1743
|
readonly hooks: hookable.Hookable<HookMap, hookable.HookKeys<HookMap>>;
|
|
1551
1744
|
private readonly listeners;
|
|
1552
|
-
/** Listeners for some collections only (2.
|
|
1745
|
+
/** Listeners for some collections only (2.3.0): they make expensive payloads be read for these collections only. */
|
|
1553
1746
|
private readonly scoped;
|
|
1554
1747
|
private readonly observers;
|
|
1555
1748
|
private readonly targets;
|
|
1556
1749
|
constructor(log?: (message: string, error: unknown) => void);
|
|
1557
1750
|
/**
|
|
1558
|
-
* Registers a listener; the returned function removes it. With `collections` (2.
|
|
1751
|
+
* Registers a listener; the returned function removes it. With `collections` (2.3.0) it only gets the events of the collections the
|
|
1559
1752
|
* function accepts, and the expensive parts of an event (old values) are only read for them.
|
|
1560
1753
|
*/
|
|
1561
1754
|
on<N extends EventName>(name: N, listener: EventListener<N>, options?: {
|
|
@@ -1633,7 +1826,7 @@ interface InterceptorBase {
|
|
|
1633
1826
|
collectionName: string;
|
|
1634
1827
|
/** The database of the collection, resolved (the default database when the path names none). */
|
|
1635
1828
|
databaseName: string;
|
|
1636
|
-
/** The user has an administrator role (2.
|
|
1829
|
+
/** The user has an administrator role (2.3.0; set by the routes, absent in payloads built elsewhere). */
|
|
1637
1830
|
isAdmin?: boolean;
|
|
1638
1831
|
}
|
|
1639
1832
|
interface WriteInterceptorPayloads {
|
|
@@ -1645,7 +1838,7 @@ interface WriteInterceptorPayloads {
|
|
|
1645
1838
|
lines?: number[];
|
|
1646
1839
|
};
|
|
1647
1840
|
/**
|
|
1648
|
-
* A document that replaces the one matched by `filter` (`PATCH …/documents/{id}`). `onNoMatch` (2.
|
|
1841
|
+
* A document that replaces the one matched by `filter` (`PATCH …/documents/{id}`). `onNoMatch` (2.3.0): called by the route when the
|
|
1649
1842
|
* write matched nothing, before it answers 404 — a hook that narrowed the filter (e.g. by a version) can explain why by throwing (409).
|
|
1650
1843
|
*/
|
|
1651
1844
|
'document:beforeReplace': InterceptorBase & {
|
|
@@ -1661,7 +1854,7 @@ interface WriteInterceptorPayloads {
|
|
|
1661
1854
|
onNoMatch?: () => void | Promise<void>;
|
|
1662
1855
|
};
|
|
1663
1856
|
/**
|
|
1664
|
-
* A delete of the documents matched by `filter`; `many` for `deleteMany`. A hook that sets `instead` (2.
|
|
1857
|
+
* A delete of the documents matched by `filter`; `many` for `deleteMany`. A hook that sets `instead` (2.3.0) turns the delete into this
|
|
1665
1858
|
* update (e.g. a deleted mark); the request is answered as a delete with the number of matched documents.
|
|
1666
1859
|
*/
|
|
1667
1860
|
'document:beforeDelete': InterceptorBase & {
|
|
@@ -1672,7 +1865,7 @@ interface WriteInterceptorPayloads {
|
|
|
1672
1865
|
};
|
|
1673
1866
|
};
|
|
1674
1867
|
/**
|
|
1675
|
-
* Every read of documents (2.
|
|
1868
|
+
* Every read of documents (2.3.0) and the target of every update, replace and delete: a hook narrows what the request may see by pushing
|
|
1676
1869
|
* conditions to `scopes` (`event.scopes.push({ tenant: 'a' })`); they are combined with the filter of the client by `$and`, so no client
|
|
1677
1870
|
* filter widens them. `filter` is the filter of the client (to look at, changing it has no effect). `withDeleted`: an administrator asked
|
|
1678
1871
|
* for soft-deleted documents too (`withDeleted=true`).
|
|
@@ -1684,8 +1877,11 @@ interface WriteInterceptorPayloads {
|
|
|
1684
1877
|
withDeleted: boolean;
|
|
1685
1878
|
};
|
|
1686
1879
|
}
|
|
1687
|
-
/**
|
|
1688
|
-
|
|
1880
|
+
/**
|
|
1881
|
+
* The kind of request a `document:beforeRead` scopes; `write` for the target of an update, replace or delete; `expand` (2.4.0) for the
|
|
1882
|
+
* documents a reference of another collection is expanded to.
|
|
1883
|
+
*/
|
|
1884
|
+
type ReadOperation = 'list' | 'search' | 'count' | 'get' | 'export' | 'distinct' | 'aggregate' | 'schema' | 'write' | 'restore' | 'watch' | 'expand';
|
|
1689
1885
|
type InterceptorName = keyof WriteInterceptorPayloads;
|
|
1690
1886
|
type WriteInterceptor<N extends InterceptorName> = (payload: WriteInterceptorPayloads[N]) => void | Promise<void>;
|
|
1691
1887
|
/**
|
|
@@ -1723,6 +1919,160 @@ declare class WriteInterceptors {
|
|
|
1723
1919
|
run<N extends InterceptorName>(name: N, payload: WriteInterceptorPayloads[N]): Promise<WriteInterceptorPayloads[N]>;
|
|
1724
1920
|
}
|
|
1725
1921
|
|
|
1922
|
+
interface InsertError {
|
|
1923
|
+
index: number;
|
|
1924
|
+
code: number;
|
|
1925
|
+
message: string;
|
|
1926
|
+
}
|
|
1927
|
+
interface ImportResponse {
|
|
1928
|
+
read: number;
|
|
1929
|
+
inserted: number;
|
|
1930
|
+
failed: number;
|
|
1931
|
+
errors: InsertError[];
|
|
1932
|
+
errorsTruncated: boolean;
|
|
1933
|
+
}
|
|
1934
|
+
declare class ImportState {
|
|
1935
|
+
read: number;
|
|
1936
|
+
inserted: number;
|
|
1937
|
+
failed: number;
|
|
1938
|
+
errors: InsertError[];
|
|
1939
|
+
errorsTruncated: boolean;
|
|
1940
|
+
/** The ids of the documents that were stored, as stored (for the compensation). */
|
|
1941
|
+
storedIds: unknown[];
|
|
1942
|
+
/** The ids as text, for the events of the caller. */
|
|
1943
|
+
get storedIdTexts(): string[];
|
|
1944
|
+
addErrors(errors: InsertError[]): void;
|
|
1945
|
+
get response(): ImportResponse;
|
|
1946
|
+
}
|
|
1947
|
+
|
|
1948
|
+
/**
|
|
1949
|
+
* How documents are written in responses (query parameter `extendedJson`).
|
|
1950
|
+
*
|
|
1951
|
+
* - `relaxed` (the default since 2.0.0) and `canonical`: MongoDB Extended JSON (`ExtendedJsonWriter.scala`), the types of ids, dates,
|
|
1952
|
+
* decimals, binary data and regular expressions stay visible (`{"$oid": ...}`, `{"$date": ...}`); canonical also wraps every number.
|
|
1953
|
+
* A text that looks like a date is written as `{"$string": ...}`, so a request body gives it back as text.
|
|
1954
|
+
* - `plain` (the default of 1.x, the format of the Scala server, `BsonConverter.asMap` + circe): ObjectIds as hex strings, dates as
|
|
1955
|
+
* ISO-8601 instants, every number as JSON number (64 bit integers and decimals with all digits), regular expressions as their pattern.
|
|
1956
|
+
*/
|
|
1957
|
+
type ExtendedJsonMode = 'relaxed' | 'canonical' | 'plain';
|
|
1958
|
+
/** The mode of the query parameter `extendedJson`; `undefined` without it (the caller picks the default). Another value is a bad request. */
|
|
1959
|
+
declare function parseExtendedJsonMode(value: string | null | undefined): ExtendedJsonMode | undefined;
|
|
1960
|
+
/** A document for a response in the mode of the query parameter `extendedJson`, relaxed Extended JSON by default. */
|
|
1961
|
+
declare function documentToJson(document: Record<string, unknown>, mode?: ExtendedJsonMode): Record<string, unknown>;
|
|
1962
|
+
|
|
1963
|
+
interface FindRequest {
|
|
1964
|
+
filter: Record<string, unknown>;
|
|
1965
|
+
sort: Record<string, unknown>;
|
|
1966
|
+
projection: Record<string, unknown>;
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
/**
|
|
1970
|
+
* The scope of a read (2.3.0): the conditions of the `document:beforeRead` hooks (soft delete, owner, tenancy of an application) combined
|
|
1971
|
+
* with the filter of the client. Every route that reads documents, and every update, replace and delete for its target, goes through it;
|
|
1972
|
+
* without a hook nothing is done.
|
|
1973
|
+
*/
|
|
1974
|
+
/** The filter with the scopes, combined by `$and`; empty parts are left out. */
|
|
1975
|
+
declare function combineScopes(filter: Document$2, scopes: readonly Document$2[]): Document$2;
|
|
1976
|
+
/** The filter of a request with the scopes of the hooks. */
|
|
1977
|
+
declare function readScope(context: Pick<MongocampContext, 'interceptors' | 'database'>, user: AuthorizedUser, collection: string, filter: Document$2, operation: ReadOperation, options?: ScopeOptions): Promise<Document$2>;
|
|
1978
|
+
interface ScopeOptions {
|
|
1979
|
+
/** Soft-deleted documents too (an administrator's `withDeleted=true`, checked by the route). */
|
|
1980
|
+
withDeleted?: boolean | undefined;
|
|
1981
|
+
}
|
|
1982
|
+
/** `withDeleted=true` of a read route (2.3.0): soft-deleted documents too, for the administrators of the collection only (403 otherwise). */
|
|
1983
|
+
declare function withDeletedOf(params: URLSearchParams, user: AuthorizedUser, collection: string): ScopeOptions;
|
|
1984
|
+
|
|
1985
|
+
interface ReadOptions extends ScopeOptions {
|
|
1986
|
+
/** The kind of request for the hooks of `document:beforeRead` (default by operation). */
|
|
1987
|
+
operation?: ReadOperation | undefined;
|
|
1988
|
+
/** References to expand (2.4.0): declared ref fields of the collection, at most `MaxExpands`. */
|
|
1989
|
+
expand?: readonly string[] | undefined;
|
|
1990
|
+
}
|
|
1991
|
+
interface PageResult {
|
|
1992
|
+
documents: Document$2[];
|
|
1993
|
+
info: PaginationInfo;
|
|
1994
|
+
}
|
|
1995
|
+
declare class DocumentService {
|
|
1996
|
+
private readonly context;
|
|
1997
|
+
constructor(context: MongocampContext);
|
|
1998
|
+
/** The collection of a name as the routes take it (`orders`, `otherdb:orders`). */
|
|
1999
|
+
collection(name: string): Collection;
|
|
2000
|
+
/** The grant of the caller; `withDeleted` only for the administrators of the collection. */
|
|
2001
|
+
private require;
|
|
2002
|
+
/** The filter with the read scope of the caller. */
|
|
2003
|
+
/** The paging of a read with `rowsPerPage` at most `PAGING_MAX_ROWS` (2.5.0, 0: no limit); the page headers show the rows used. */
|
|
2004
|
+
private limited;
|
|
2005
|
+
/** Refuses filters, projections and updates of the caller with an operator of `FILTER_OPERATORS_DENIED` (2.5.0). */
|
|
2006
|
+
private checkOperators;
|
|
2007
|
+
scope(user: AuthorizedUser, collection: string, filter: Document$2, operation: ReadOperation, options?: ScopeOptions): Promise<Document$2>;
|
|
2008
|
+
/**
|
|
2009
|
+
* The declared references of `fields` (2.4.0); 400 for a name that is no reference of the collection and for more than `MaxExpands`.
|
|
2010
|
+
* Checked before anything is read.
|
|
2011
|
+
*/
|
|
2012
|
+
refs(collection: string, fields: readonly string[] | undefined): ResolvedRef[];
|
|
2013
|
+
/**
|
|
2014
|
+
* Replaces the references of the documents by the documents they point to (2.4.0). Each target is read once per reference (`$in` of the
|
|
2015
|
+
* ids) with the grant and the read scope of the **target** for the same user, without its secret fields: a reference the user cannot
|
|
2016
|
+
* read directly becomes `null` (an array leaves it out), so an expansion never shows more than a direct read.
|
|
2017
|
+
*/
|
|
2018
|
+
expand(user: AuthorizedUser, documents: Document$2[], refs: readonly ResolvedRef[]): Promise<Document$2[]>;
|
|
2019
|
+
/** A page of documents (list, find, search), with the references of `options.expand` expanded. */
|
|
2020
|
+
page(user: AuthorizedUser, collection: string, request: FindRequest, paging: Paging, count?: CountMode, options?: ReadOptions): Promise<PageResult>;
|
|
2021
|
+
/** The number of documents of a filter. */
|
|
2022
|
+
count(user: AuthorizedUser, collection: string, filter: Document$2, options?: ReadOptions): Promise<number>;
|
|
2023
|
+
/** One document by the id of the path (any type of id), `null` when it is missing or not in the scope of the caller. */
|
|
2024
|
+
get(user: AuthorizedUser, collection: string, id: string, options?: ReadOptions): Promise<Document$2 | null>;
|
|
2025
|
+
/** The filter of an export with the scope, and the scope alone (for the column sample of a csv export). */
|
|
2026
|
+
exportFilter(user: AuthorizedUser, collection: string, filter: Document$2, options?: ReadOptions): Promise<{
|
|
2027
|
+
filter: Document$2;
|
|
2028
|
+
scope: Document$2;
|
|
2029
|
+
}>;
|
|
2030
|
+
/** The distinct values of a field, as aggregation results `{ _id, field }`. */
|
|
2031
|
+
distinct(user: AuthorizedUser, collection: string, field: string, paging: Paging, count?: CountMode, options?: ReadOptions): Promise<PageResult>;
|
|
2032
|
+
/**
|
|
2033
|
+
* An aggregation: `prefix` (the client's filter, the unset of secrets) and the stages of the client, after the scope of the caller as
|
|
2034
|
+
* first `$match`. The checks of the pipeline (denied stages) are the route's.
|
|
2035
|
+
*/
|
|
2036
|
+
aggregate(user: AuthorizedUser, collection: string, prefix: Document$2[], stages: Document$2[], allowDiskUse: boolean, paging: Paging, count?: CountMode, options?: ReadOptions): Promise<PageResult>;
|
|
2037
|
+
/**
|
|
2038
|
+
* Runs the before-hooks of a write (after auth and decoding, before the old values are read and the write is done) and answers the
|
|
2039
|
+
* payload with their changes. A hook that refuses the write throws.
|
|
2040
|
+
*/
|
|
2041
|
+
private intercept;
|
|
2042
|
+
/**
|
|
2043
|
+
* The insert hooks: they may change the documents, but not their number (the errors of an insert and of an import name the documents by
|
|
2044
|
+
* their position). A hook that does not want a document refuses the write.
|
|
2045
|
+
*/
|
|
2046
|
+
private interceptInsert;
|
|
2047
|
+
/** The documents before a change, read only when a listener waits for them; at most `MaxOldValues`. */
|
|
2048
|
+
private oldValues;
|
|
2049
|
+
/** Deletes the documents of the filter, or applies the update of a before-hook instead (soft delete); answers the number of documents. */
|
|
2050
|
+
private deleteOrInstead;
|
|
2051
|
+
private inserted;
|
|
2052
|
+
private updated;
|
|
2053
|
+
private deleted;
|
|
2054
|
+
/** Inserts one document (decoded). */
|
|
2055
|
+
insert(user: AuthorizedUser, collection: string, document: Document$2): Promise<Schemas['InsertResponse']>;
|
|
2056
|
+
/** Inserts documents; `ordered: false` stores the ones that can be stored and reports the others in `errors`. */
|
|
2057
|
+
insertMany(user: AuthorizedUser, collection: string, input: Document$2[], ordered?: boolean): Promise<Schemas['InsertResponse']>;
|
|
2058
|
+
/** Imports the lines of a body stream (all or nothing); the hooks see the valid documents of each batch. */
|
|
2059
|
+
import(user: AuthorizedUser, collection: string, body: ReadableStream<Uint8Array> | null, maxBytes: number): Promise<ImportState>;
|
|
2060
|
+
/** Replaces the document of the path id (decoded body); 404 when it is missing or not in the scope, 409 of a version check. */
|
|
2061
|
+
replace(user: AuthorizedUser, collection: string, id: string, body: Document$2): Promise<Schemas['UpdateResponse']>;
|
|
2062
|
+
/** Changes the document of the path id with an operator update (`$set`, ...). */
|
|
2063
|
+
update(user: AuthorizedUser, collection: string, id: string, operators: Document$2): Promise<Schemas['UpdateResponse']>;
|
|
2064
|
+
/** Changes the documents of a filter (checked by the caller: not empty unless intended). */
|
|
2065
|
+
updateMany(user: AuthorizedUser, collection: string, filter: Document$2, operators: Document$2): Promise<Schemas['UpdateResponse']>;
|
|
2066
|
+
/** Deletes the document of the path id (or marks it, soft delete); 404 when it is missing or not in the scope. */
|
|
2067
|
+
remove(user: AuthorizedUser, collection: string, id: string): Promise<Schemas['DeleteResponse']>;
|
|
2068
|
+
/** Deletes the documents of a filter (checked by the caller). */
|
|
2069
|
+
removeMany(user: AuthorizedUser, collection: string, filter: Document$2): Promise<Schemas['DeleteResponse']>;
|
|
2070
|
+
/** Brings a soft-deleted document back (collections declared with softDelete). */
|
|
2071
|
+
restore(user: AuthorizedUser, collection: string, id: string): Promise<Schemas['UpdateResponse']>;
|
|
2072
|
+
/** The audit records of a filter (a document or the collection), newest first. */
|
|
2073
|
+
auditRecords(filter: Document$2, paging: Paging, count?: CountMode): Promise<PageResult>;
|
|
2074
|
+
}
|
|
2075
|
+
|
|
1726
2076
|
/**
|
|
1727
2077
|
* Jobs (`JobPlugin.scala`, `JobRoutes.scala`) on croner. A job is a document `JobConfig` in `<AUTH_PREFIX>jobs`; its `className` names a
|
|
1728
2078
|
* handler of the registry (the Scala server loaded JVM classes). Cron expressions use the syntax of croner: 5, 6 or 7 fields (seconds and
|
|
@@ -1863,17 +2213,92 @@ interface MongocampContext {
|
|
|
1863
2213
|
events: EventBus;
|
|
1864
2214
|
/** The before-hooks of the document writes (awaited, may change or refuse a write). */
|
|
1865
2215
|
interceptors: WriteInterceptors;
|
|
2216
|
+
/** The documents of the collections for one caller, without HTTP (2.4.0): the routes and the server collection use it. */
|
|
2217
|
+
documents: DocumentService;
|
|
1866
2218
|
/** The declared collections (`server.use(collections([...]))`), empty without. */
|
|
1867
2219
|
collections: CollectionRegistry;
|
|
1868
2220
|
jobs: JobScheduler;
|
|
1869
2221
|
/** The metrics, with `METRICS_ENABLED` only. */
|
|
1870
|
-
metrics?: MongocampMetrics;
|
|
2222
|
+
metrics?: MongocampMetrics | undefined;
|
|
1871
2223
|
/** The answer of `buildInfo`, kept for an hour. */
|
|
1872
2224
|
systemInfo: InfoCache<SystemInfo>;
|
|
1873
2225
|
/** Stops the process (`DELETE /system`); not set when the server is embedded in an application. */
|
|
1874
|
-
shutdown?: (force: boolean) => void | Promise<void
|
|
2226
|
+
shutdown?: ((force: boolean) => void | Promise<void>) | undefined;
|
|
1875
2227
|
}
|
|
1876
2228
|
|
|
2229
|
+
/**
|
|
2230
|
+
* The documents of a collection in server code (2.4.0): `server.collection('orders', { user })` — the same operations as the API
|
|
2231
|
+
* (`DocumentService`), so grants, the read scope (owner, soft delete, hooks), validation, the behaviours (timestamps, version, audit) and
|
|
2232
|
+
* the events are the same as for a request of that user. No HTTP, no JSON: documents come and go as driver values (`ObjectId`, `Date`;
|
|
2233
|
+
* numbers as JavaScript numbers).
|
|
2234
|
+
*
|
|
2235
|
+
* For writes that must not go through the rules (migrations, bulk scripts) use the driver (`server.context.database`).
|
|
2236
|
+
*/
|
|
2237
|
+
/**
|
|
2238
|
+
* Who works with the collection: a user id, an authorized user, a `Request` (its credentials; in Nitro the request of the event), or
|
|
2239
|
+
* `'system'` — an administrator without grant checks and owner rules, for jobs and seeds.
|
|
2240
|
+
*/
|
|
2241
|
+
type ServerCollectionUser = string | AuthorizedUser | Request | 'system';
|
|
2242
|
+
interface ServerCollectionOptions {
|
|
2243
|
+
user: ServerCollectionUser;
|
|
2244
|
+
}
|
|
2245
|
+
interface ServerFindOptions {
|
|
2246
|
+
/** A MongoDB filter, or a Lucene filter as text (`status:open AND qty:[1 TO 5]`). */
|
|
2247
|
+
filter?: Document$2 | string;
|
|
2248
|
+
/** `{ field: 1 | -1 }` or fields with `-` for descending. */
|
|
2249
|
+
sort?: Document$2 | string[];
|
|
2250
|
+
projection?: Document$2 | string[];
|
|
2251
|
+
page?: number;
|
|
2252
|
+
rowsPerPage?: number;
|
|
2253
|
+
count?: CountMode;
|
|
2254
|
+
/** Soft-deleted documents too (administrators of the collection). */
|
|
2255
|
+
withDeleted?: boolean;
|
|
2256
|
+
/** References to expand (2.4.0): declared ref fields, read with the grant and scope of their collection. */
|
|
2257
|
+
expand?: readonly string[];
|
|
2258
|
+
}
|
|
2259
|
+
interface ServerPage<T> {
|
|
2260
|
+
documents: T[];
|
|
2261
|
+
page: number;
|
|
2262
|
+
rowsPerPage: number;
|
|
2263
|
+
countRows?: number;
|
|
2264
|
+
countPages?: number;
|
|
2265
|
+
}
|
|
2266
|
+
/** A document that was read (with `_id`), or its id. */
|
|
2267
|
+
/** An id, or a document that was read (its `_id`; the schema type of a declared collection has an optional `_id`). */
|
|
2268
|
+
type ServerDocumentIdentity = string | number | ObjectId | {
|
|
2269
|
+
_id?: unknown;
|
|
2270
|
+
};
|
|
2271
|
+
interface ServerCollection<T, I = T> {
|
|
2272
|
+
readonly name: string;
|
|
2273
|
+
find: (options?: ServerFindOptions) => Promise<T[]>;
|
|
2274
|
+
findPage: (options?: ServerFindOptions) => Promise<ServerPage<T>>;
|
|
2275
|
+
/** The document, `null` when it is missing or not in the scope of the user. */
|
|
2276
|
+
findById: (id: ServerDocumentIdentity, options?: {
|
|
2277
|
+
withDeleted?: boolean;
|
|
2278
|
+
expand?: readonly string[];
|
|
2279
|
+
}) => Promise<T | null>;
|
|
2280
|
+
count: (filter?: Document$2 | string, options?: {
|
|
2281
|
+
withDeleted?: boolean;
|
|
2282
|
+
}) => Promise<number>;
|
|
2283
|
+
insert: (document: I) => Promise<Schemas['InsertResponse']>;
|
|
2284
|
+
insertMany: (documents: I[], options?: {
|
|
2285
|
+
ordered?: boolean;
|
|
2286
|
+
}) => Promise<Schemas['InsertResponse']>;
|
|
2287
|
+
/** Replaces the document; given the document that was read, its version is checked (409 when someone changed it in between). */
|
|
2288
|
+
replace: (target: ServerDocumentIdentity, document: I) => Promise<Schemas['UpdateResponse']>;
|
|
2289
|
+
/** Sets the given fields (`null` removes one); given the document that was read, its version is checked. */
|
|
2290
|
+
update: (target: ServerDocumentIdentity, changes: Partial<T>) => Promise<Schemas['UpdateResponse']>;
|
|
2291
|
+
updateMany: (filter: Document$2 | string, changes: Partial<T>) => Promise<Schemas['UpdateResponse']>;
|
|
2292
|
+
remove: (target: ServerDocumentIdentity) => Promise<Schemas['DeleteResponse']>;
|
|
2293
|
+
removeMany: (filter: Document$2 | string) => Promise<Schemas['DeleteResponse']>;
|
|
2294
|
+
restore: (target: ServerDocumentIdentity) => Promise<Schemas['UpdateResponse']>;
|
|
2295
|
+
/** The audit records of the document, newest first (collections declared with `audit`). */
|
|
2296
|
+
history: (target: ServerDocumentIdentity) => Promise<Document$2[]>;
|
|
2297
|
+
}
|
|
2298
|
+
/** The administrator of server code: every grant, no owner rule (`adminBypass`). */
|
|
2299
|
+
declare const SystemUser: AuthorizedUser;
|
|
2300
|
+
declare function createServerCollection<T = Document$2, I = T>(context: MongocampContext, name: string, options: ServerCollectionOptions): ServerCollection<T, I>;
|
|
2301
|
+
|
|
1877
2302
|
interface MongocampServerOptions extends DatabaseOptions {
|
|
1878
2303
|
/** Environment variables, `process.env` when omitted. */
|
|
1879
2304
|
env?: ConfigSources['env'];
|
|
@@ -1948,30 +2373,16 @@ interface MongocampServer {
|
|
|
1948
2373
|
* same name is used once; it is stopped by `close`.
|
|
1949
2374
|
*/
|
|
1950
2375
|
use: (feature: MongocampFeature) => Promise<void>;
|
|
2376
|
+
/**
|
|
2377
|
+
* The documents of a collection for a user in server code (2.4.0): the same grants, scope, validation, behaviours and events as the API.
|
|
2378
|
+
* `user`: an id, an authorized user, a request (its credentials) or `'system'`.
|
|
2379
|
+
*/
|
|
2380
|
+
collection: <T = Record<string, unknown>, I = T>(name: string, options: ServerCollectionOptions) => ServerCollection<T, I>;
|
|
1951
2381
|
close: () => Promise<void>;
|
|
1952
2382
|
}
|
|
1953
2383
|
/** Creates and connects a MongoCamp server. */
|
|
1954
2384
|
declare function createMongocampServer(options?: MongocampServerOptions): Promise<MongocampServer>;
|
|
1955
2385
|
|
|
1956
|
-
/** The fields of the server in the wide event of a request (key `mongocamp`). */
|
|
1957
|
-
interface MongocampRequestFields {
|
|
1958
|
-
requestId: string;
|
|
1959
|
-
/** The operationId of the OpenAPI spec (`listDocuments`), `NOT_SET` for an unknown route. */
|
|
1960
|
-
operation: string;
|
|
1961
|
-
controller: string;
|
|
1962
|
-
/** The user the request was authenticated as; missing for public routes and invalid credentials. */
|
|
1963
|
-
user?: string;
|
|
1964
|
-
database?: string;
|
|
1965
|
-
collection?: string;
|
|
1966
|
-
bucket?: string;
|
|
1967
|
-
/** All matching rows of a paged list (`x-pagination-count-rows`). */
|
|
1968
|
-
rows?: number;
|
|
1969
|
-
/** `x-error-code` and `x-error-message` of an error response. */
|
|
1970
|
-
errorCode?: string;
|
|
1971
|
-
errorMessage?: string;
|
|
1972
|
-
}
|
|
1973
|
-
declare function requestFields(request: Request, response: Response, fields: HttpRequestFields, user: string | undefined): MongocampRequestFields;
|
|
1974
|
-
|
|
1975
2386
|
/** Error codes of the API (`mongocamp-library/.../exception/ErrorCodes.scala`), sent in `ErrorDescription.code` and `x-error-code`. */
|
|
1976
2387
|
declare const ErrorCodes: {
|
|
1977
2388
|
/** A request that could not be decoded (body, query or header with an invalid value). */
|
|
@@ -1987,15 +2398,15 @@ declare const ErrorCodes: {
|
|
|
1987
2398
|
/** A document that a schema or a before-hook refuses; `ErrorDescription.issues` names the fields (the validator of MongoDB answers 121). */
|
|
1988
2399
|
readonly validationFailed: 4010;
|
|
1989
2400
|
readonly collectionExists: 4091;
|
|
1990
|
-
/** A write based on an outdated version of a versioned document (2.
|
|
2401
|
+
/** A write based on an outdated version of a versioned document (2.3.0); `ErrorDescription.current` is the stored document. */
|
|
1991
2402
|
readonly versionConflict: 4092;
|
|
1992
|
-
/** A versioned collection with `required: true` got a write without version (2.
|
|
2403
|
+
/** A versioned collection with `required: true` got a write without version (2.3.0). */
|
|
1993
2404
|
readonly versionRequired: 4281;
|
|
1994
2405
|
readonly badInsertRequest: 4401;
|
|
1995
2406
|
readonly idMissingForReplace: 4402;
|
|
1996
2407
|
readonly authMethodNotImplemented: 5001;
|
|
1997
2408
|
readonly mvnRepositoryConfigurationInvalid: 5002;
|
|
1998
|
-
/** Live updates need change streams: a replica set or a sharded cluster (2.
|
|
2409
|
+
/** Live updates need change streams: a replica set or a sharded cluster (2.3.0). */
|
|
1999
2410
|
readonly changeStreamsUnsupported: 5011;
|
|
2000
2411
|
readonly unauthorizedUser: 4011;
|
|
2001
2412
|
readonly unauthorizedUserForOtherUser: 4012;
|
|
@@ -2007,6 +2418,106 @@ declare const ErrorCodes: {
|
|
|
2007
2418
|
readonly jobClassNotFound: 4042;
|
|
2008
2419
|
};
|
|
2009
2420
|
|
|
2421
|
+
/**
|
|
2422
|
+
* The behaviour `audit` (2.3.0): every write to the collection leaves a record with the operation, the user, the time and the document
|
|
2423
|
+
* before and after, in `<AUTH_PREFIX>audit` of the default database, kept for `retentionDays` (a TTL index on `expiresAt`).
|
|
2424
|
+
*
|
|
2425
|
+
* Built on the events, so it is best effort like them: written after the request is answered, a failure is logged and does not fail the
|
|
2426
|
+
* write. A write of many documents records up to `MaxOldValues` documents and one summary record with the count. An import records the
|
|
2427
|
+
* ids of the documents only.
|
|
2428
|
+
*/
|
|
2429
|
+
type AuditOperation = 'insert' | 'replace' | 'update' | 'delete' | 'softDelete' | 'restore';
|
|
2430
|
+
interface AuditRecord {
|
|
2431
|
+
collection: string;
|
|
2432
|
+
database: string;
|
|
2433
|
+
/** The `_id` of the document; absent on a summary record. */
|
|
2434
|
+
documentId?: unknown;
|
|
2435
|
+
operation: AuditOperation;
|
|
2436
|
+
user: string;
|
|
2437
|
+
at: Date;
|
|
2438
|
+
before?: Document$2;
|
|
2439
|
+
after?: Document$2;
|
|
2440
|
+
/** A summary of a write of many documents: the number of documents and how many of them have a record. */
|
|
2441
|
+
summary?: {
|
|
2442
|
+
count: number;
|
|
2443
|
+
recorded: number;
|
|
2444
|
+
};
|
|
2445
|
+
/** When MongoDB deletes the record (TTL). */
|
|
2446
|
+
expiresAt: Date;
|
|
2447
|
+
}
|
|
2448
|
+
declare const AuditCollection = "audit";
|
|
2449
|
+
/** The audit records of the server: `<AUTH_PREFIX>audit` in the default database. */
|
|
2450
|
+
declare function auditCollectionOf<T extends Document$2 = AuditRecord>(context: Pick<MongocampContext, 'database'>): Collection<T>;
|
|
2451
|
+
/** The records of one write. */
|
|
2452
|
+
declare function auditRecords(input: {
|
|
2453
|
+
declared: DeclaredCollection;
|
|
2454
|
+
operation: AuditOperation;
|
|
2455
|
+
user: string;
|
|
2456
|
+
at: Date;
|
|
2457
|
+
documents: Array<{
|
|
2458
|
+
before?: Document$2 | undefined;
|
|
2459
|
+
after?: Document$2 | undefined;
|
|
2460
|
+
}>;
|
|
2461
|
+
count?: number;
|
|
2462
|
+
}): AuditRecord[];
|
|
2463
|
+
/** Creates the indexes of the audit records (history per document, TTL); idempotent. */
|
|
2464
|
+
declare function ensureAuditIndexes(context: Pick<MongocampContext, 'database' | 'logger'>): Promise<void>;
|
|
2465
|
+
|
|
2466
|
+
/**
|
|
2467
|
+
* The events of the server as hooks of a Nitro app (or any `hookable` instance): `mongocamp:document:update`, ... and `mongocamp:ready` with
|
|
2468
|
+
* the server once it is started. The before-hooks of the writes (`mongocamp:document:beforeInsert`, ...) are awaited and may change the
|
|
2469
|
+
* payload in place or refuse the write by throwing (see `WriteInterceptors`). An extension of an application is then a plain Nitro plugin:
|
|
2470
|
+
*
|
|
2471
|
+
* export default definePlugin((nitroApp) => {
|
|
2472
|
+
* nitroApp.hooks.hook('mongocamp:ready', server => server.use(metrics()))
|
|
2473
|
+
* nitroApp.hooks.hook('mongocamp:document:delete', event => audit(event))
|
|
2474
|
+
* nitroApp.hooks.hook('mongocamp:document:beforeInsert', ({ documents, user }) => documents.forEach(d => d.createdBy = user.userId))
|
|
2475
|
+
* })
|
|
2476
|
+
*/
|
|
2477
|
+
type MongocampHooks = {
|
|
2478
|
+
'mongocamp:ready': (server: MongocampServer) => void | Promise<void>;
|
|
2479
|
+
} & {
|
|
2480
|
+
[N in EventName as `mongocamp:${N}`]: (event: MongocampEvent<N>) => void | Promise<void>;
|
|
2481
|
+
} & {
|
|
2482
|
+
[N in InterceptorName as `mongocamp:${N}`]: (payload: WriteInterceptorPayloads[N]) => void | Promise<void>;
|
|
2483
|
+
};
|
|
2484
|
+
/** The part of `hookable` (Nitro's `nitroApp.hooks`) the bridge needs. */
|
|
2485
|
+
interface HookSystem {
|
|
2486
|
+
callHook(name: string, ...args: unknown[]): unknown;
|
|
2487
|
+
}
|
|
2488
|
+
declare const HookPrefix = "mongocamp:";
|
|
2489
|
+
/** Calls `mongocamp:<event>` for every event of the server that has a hook listener; the returned function stops it. */
|
|
2490
|
+
declare function forwardEventsToHooks(server: Pick<MongocampServer, 'events'>, hooks: HookSystem): () => void;
|
|
2491
|
+
/**
|
|
2492
|
+
* Runs `mongocamp:document:beforeInsert`, ... of the hook system as interceptors of the writes (awaited, an error refuses the write); only
|
|
2493
|
+
* hooks with a listener cost anything. The returned function stops it.
|
|
2494
|
+
*/
|
|
2495
|
+
declare function forwardInterceptorsToHooks(server: Pick<MongocampServer, 'interceptors'>, hooks: HookSystem): () => void;
|
|
2496
|
+
/**
|
|
2497
|
+
* Connects a started server with the hooks of its host: forwards the events and the interceptors, and calls `mongocamp:ready` (awaited, so
|
|
2498
|
+
* features that the plugins switch on are active before the first request is answered).
|
|
2499
|
+
*/
|
|
2500
|
+
declare function connectHooks(server: MongocampServer, hooks: HookSystem): Promise<() => void>;
|
|
2501
|
+
|
|
2502
|
+
/** The fields of the server in the wide event of a request (key `mongocamp`). */
|
|
2503
|
+
interface MongocampRequestFields {
|
|
2504
|
+
requestId: string;
|
|
2505
|
+
/** The operationId of the OpenAPI spec (`listDocuments`), `NOT_SET` for an unknown route. */
|
|
2506
|
+
operation: string;
|
|
2507
|
+
controller: string;
|
|
2508
|
+
/** The user the request was authenticated as; missing for public routes and invalid credentials. */
|
|
2509
|
+
user?: string;
|
|
2510
|
+
database?: string;
|
|
2511
|
+
collection?: string;
|
|
2512
|
+
bucket?: string;
|
|
2513
|
+
/** All matching rows of a paged list (`x-pagination-count-rows`). */
|
|
2514
|
+
rows?: number;
|
|
2515
|
+
/** `x-error-code` and `x-error-message` of an error response. */
|
|
2516
|
+
errorCode?: string;
|
|
2517
|
+
errorMessage?: string;
|
|
2518
|
+
}
|
|
2519
|
+
declare function requestFields(request: Request, response: Response, fields: HttpRequestFields, user: string | undefined): MongocampRequestFields;
|
|
2520
|
+
|
|
2010
2521
|
/** The key of the wrapper `{"$string": "..."}`: a text that looks like a date stays a text (`CirceSchema.TextMarker`). */
|
|
2011
2522
|
declare const TextMarker = "$string";
|
|
2012
2523
|
/**
|
|
@@ -2046,21 +2557,6 @@ declare function convertIdValue(id: unknown): unknown;
|
|
|
2046
2557
|
*/
|
|
2047
2558
|
declare function pathIdFilter(id: string): PlainObject;
|
|
2048
2559
|
|
|
2049
|
-
/**
|
|
2050
|
-
* How documents are written in responses (query parameter `extendedJson`).
|
|
2051
|
-
*
|
|
2052
|
-
* - `relaxed` (the default since 2.0.0) and `canonical`: MongoDB Extended JSON (`ExtendedJsonWriter.scala`), the types of ids, dates,
|
|
2053
|
-
* decimals, binary data and regular expressions stay visible (`{"$oid": ...}`, `{"$date": ...}`); canonical also wraps every number.
|
|
2054
|
-
* A text that looks like a date is written as `{"$string": ...}`, so a request body gives it back as text.
|
|
2055
|
-
* - `plain` (the default of 1.x, the format of the Scala server, `BsonConverter.asMap` + circe): ObjectIds as hex strings, dates as
|
|
2056
|
-
* ISO-8601 instants, every number as JSON number (64 bit integers and decimals with all digits), regular expressions as their pattern.
|
|
2057
|
-
*/
|
|
2058
|
-
type ExtendedJsonMode = 'relaxed' | 'canonical' | 'plain';
|
|
2059
|
-
/** The mode of the query parameter `extendedJson`; `undefined` without it (the caller picks the default). Another value is a bad request. */
|
|
2060
|
-
declare function parseExtendedJsonMode(value: string | null | undefined): ExtendedJsonMode | undefined;
|
|
2061
|
-
/** A document for a response in the mode of the query parameter `extendedJson`, relaxed Extended JSON by default. */
|
|
2062
|
-
declare function documentToJson(document: Record<string, unknown>, mode?: ExtendedJsonMode): Record<string, unknown>;
|
|
2063
|
-
|
|
2064
2560
|
/**
|
|
2065
2561
|
* The queries that the Lucene parser produces (the subset of `org.apache.lucene.search.Query` that `LuceneQueryConverter` knows),
|
|
2066
2562
|
* plus the kinds it does not support, which fail in the converter like in the Scala driver.
|
|
@@ -2198,7 +2694,7 @@ declare const bsonMarkerOptions: {
|
|
|
2198
2694
|
};
|
|
2199
2695
|
/**
|
|
2200
2696
|
* The `$jsonSchema` of a declaration: its `validator`, else converted from the JSON Schema of its schema; with the fields of its behaviours
|
|
2201
|
-
* added (2.
|
|
2697
|
+
* added (2.3.0, see `withSystemFields`) unless `systemFields: false`.
|
|
2202
2698
|
*/
|
|
2203
2699
|
declare function validatorOf(definition: MongocampCollectionDefinition, options?: {
|
|
2204
2700
|
systemFields?: boolean;
|
|
@@ -2213,7 +2709,7 @@ declare function withSystemFields(jsonSchema: Document$2, behaviours: ResolvedBe
|
|
|
2213
2709
|
declare function toMongoJsonSchema(root: Record<string, unknown>): ConversionResult;
|
|
2214
2710
|
|
|
2215
2711
|
/**
|
|
2216
|
-
* What clients may not write (2.
|
|
2712
|
+
* What clients may not write (2.3.0): the fields of behaviours (timestamps, owner, version, deleted mark) and the `protectedFields` of a
|
|
2217
2713
|
* declaration. The guard runs first (stage `guard`), so before-hooks and Nitro hooks of the application can still set protected fields;
|
|
2218
2714
|
* writes with the driver (`useMongocampCore()`, scripts) are not checked at all.
|
|
2219
2715
|
*
|
|
@@ -2237,23 +2733,7 @@ declare function stripDocument(document: Document$2, paths: readonly string[]):
|
|
|
2237
2733
|
declare function stripUpdate(update: Document$2, guarded: readonly string[], system: readonly string[]): Document$2;
|
|
2238
2734
|
|
|
2239
2735
|
/**
|
|
2240
|
-
* The
|
|
2241
|
-
* with the filter of the client. Every route that reads documents, and every update, replace and delete for its target, goes through it;
|
|
2242
|
-
* without a hook nothing is done.
|
|
2243
|
-
*/
|
|
2244
|
-
/** The filter with the scopes, combined by `$and`; empty parts are left out. */
|
|
2245
|
-
declare function combineScopes(filter: Document$2, scopes: readonly Document$2[]): Document$2;
|
|
2246
|
-
/** The filter of a request with the scopes of the hooks. */
|
|
2247
|
-
declare function readScope(context: Pick<MongocampContext, 'interceptors' | 'database'>, user: AuthorizedUser, collection: string, filter: Document$2, operation: ReadOperation, options?: ScopeOptions): Promise<Document$2>;
|
|
2248
|
-
interface ScopeOptions {
|
|
2249
|
-
/** Soft-deleted documents too (an administrator's `withDeleted=true`, checked by the route). */
|
|
2250
|
-
withDeleted?: boolean;
|
|
2251
|
-
}
|
|
2252
|
-
/** `withDeleted=true` of a read route (2.4.0): soft-deleted documents too, for the administrators of the collection only (403 otherwise). */
|
|
2253
|
-
declare function withDeletedOf(params: URLSearchParams, user: AuthorizedUser, collection: string): ScopeOptions;
|
|
2254
|
-
|
|
2255
|
-
/**
|
|
2256
|
-
* The behaviour `softDelete` (2.4.0): a delete sets the deleted mark (`deletedAt`) instead of removing the document, every read hides
|
|
2736
|
+
* The behaviour `softDelete` (2.3.0): a delete sets the deleted mark (`deletedAt`) instead of removing the document, every read hides
|
|
2257
2737
|
* marked documents (`document:beforeRead`), an administrator sees them with `withDeleted=true`, `POST …/documents/{id}/restore` removes
|
|
2258
2738
|
* the mark, and `purgeAfterDays` removes marked documents for good (a TTL index).
|
|
2259
2739
|
*/
|
|
@@ -2274,7 +2754,7 @@ declare function purgeIndexName(softDelete: SoftDelete): string;
|
|
|
2274
2754
|
declare function syncPurgeIndex(db: Db, declared: DeclaredCollection, logger: MongocampLogger): Promise<'created' | 'changed' | 'dropped' | 'unchanged' | 'failed'>;
|
|
2275
2755
|
|
|
2276
2756
|
/**
|
|
2277
|
-
* The behaviour `owner` (2.
|
|
2757
|
+
* The behaviour `owner` (2.3.0): every document belongs to the user who created it. Only the owner changes, replaces, deletes and restores
|
|
2278
2758
|
* it; reads follow `read` — `own` (default) the owner only, `all` everybody with the read grant, or a function of the application.
|
|
2279
2759
|
* A document of someone else is answered like a missing one (404), so nobody learns which ids exist. Administrators read and write every
|
|
2280
2760
|
* document (`adminBypass`, default true). The collection grants still apply first: owner rules narrow them, never widen them.
|
|
@@ -2286,52 +2766,7 @@ type Owner = NonNullable<ResolvedBehaviours['owner']>;
|
|
|
2286
2766
|
declare function ownedBy(owner: Owner, userId: string): Document$2;
|
|
2287
2767
|
|
|
2288
2768
|
/**
|
|
2289
|
-
* The behaviour `
|
|
2290
|
-
* before and after, in `<AUTH_PREFIX>audit` of the default database, kept for `retentionDays` (a TTL index on `expiresAt`).
|
|
2291
|
-
*
|
|
2292
|
-
* Built on the events, so it is best effort like them: written after the request is answered, a failure is logged and does not fail the
|
|
2293
|
-
* write. A write of many documents records up to `MaxOldValues` documents and one summary record with the count. An import records the
|
|
2294
|
-
* ids of the documents only.
|
|
2295
|
-
*/
|
|
2296
|
-
type AuditOperation = 'insert' | 'replace' | 'update' | 'delete' | 'softDelete' | 'restore';
|
|
2297
|
-
interface AuditRecord {
|
|
2298
|
-
collection: string;
|
|
2299
|
-
database: string;
|
|
2300
|
-
/** The `_id` of the document; absent on a summary record. */
|
|
2301
|
-
documentId?: unknown;
|
|
2302
|
-
operation: AuditOperation;
|
|
2303
|
-
user: string;
|
|
2304
|
-
at: Date;
|
|
2305
|
-
before?: Document$2;
|
|
2306
|
-
after?: Document$2;
|
|
2307
|
-
/** A summary of a write of many documents: the number of documents and how many of them have a record. */
|
|
2308
|
-
summary?: {
|
|
2309
|
-
count: number;
|
|
2310
|
-
recorded: number;
|
|
2311
|
-
};
|
|
2312
|
-
/** When MongoDB deletes the record (TTL). */
|
|
2313
|
-
expiresAt: Date;
|
|
2314
|
-
}
|
|
2315
|
-
declare const AuditCollection = "audit";
|
|
2316
|
-
/** The audit records of the server: `<AUTH_PREFIX>audit` in the default database. */
|
|
2317
|
-
declare function auditCollectionOf(context: Pick<MongocampContext, 'database'>): Collection<AuditRecord>;
|
|
2318
|
-
/** The records of one write. */
|
|
2319
|
-
declare function auditRecords(input: {
|
|
2320
|
-
declared: DeclaredCollection;
|
|
2321
|
-
operation: AuditOperation;
|
|
2322
|
-
user: string;
|
|
2323
|
-
at: Date;
|
|
2324
|
-
documents: Array<{
|
|
2325
|
-
before?: Document$2;
|
|
2326
|
-
after?: Document$2;
|
|
2327
|
-
}>;
|
|
2328
|
-
count?: number;
|
|
2329
|
-
}): AuditRecord[];
|
|
2330
|
-
/** Creates the indexes of the audit records (history per document, TTL); idempotent. */
|
|
2331
|
-
declare function ensureAuditIndexes(context: Pick<MongocampContext, 'database' | 'logger'>): Promise<void>;
|
|
2332
|
-
|
|
2333
|
-
/**
|
|
2334
|
-
* The behaviour `versioned` (2.4.0): a replace or partial update that sends the version of the document it is based on only succeeds when
|
|
2769
|
+
* The behaviour `versioned` (2.3.0): a replace or partial update that sends the version of the document it is based on only succeeds when
|
|
2335
2770
|
* the document still has that version; otherwise it answers 409 with the stored document (`current`) instead of overwriting the change of
|
|
2336
2771
|
* someone else. In the same write, no read-then-write race.
|
|
2337
2772
|
*
|
|
@@ -2352,7 +2787,7 @@ declare function withVersion(filter: Document$2, versioned: Versioned, version:
|
|
|
2352
2787
|
declare function withIncrement(update: Document$2, versioned: Versioned): Document$2;
|
|
2353
2788
|
|
|
2354
2789
|
/**
|
|
2355
|
-
* The behaviour `timestamps` (2.
|
|
2790
|
+
* The behaviour `timestamps` (2.3.0): the server writes the creation and change time and, when configured, the user of the request
|
|
2356
2791
|
* (`createdBy`, `updatedBy`) on every write path. Runs in the stage `system`, after the validation, and after the guard put the stored
|
|
2357
2792
|
* values of a replace back — so the creation values survive every later write. Clients cannot send these fields (guard).
|
|
2358
2793
|
*/
|
|
@@ -2372,41 +2807,5 @@ declare function stampReplace(document: Document$2, timestamps: Timestamps, stam
|
|
|
2372
2807
|
/** An update with the change fields set (`$set` with dot paths, so the creation fields next to them stay). */
|
|
2373
2808
|
declare function stampUpdate(update: Document$2, timestamps: Timestamps, stamp: WriteStamp): Document$2;
|
|
2374
2809
|
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
* the server once it is started. The before-hooks of the writes (`mongocamp:document:beforeInsert`, ...) are awaited and may change the
|
|
2378
|
-
* payload in place or refuse the write by throwing (see `WriteInterceptors`). An extension of an application is then a plain Nitro plugin:
|
|
2379
|
-
*
|
|
2380
|
-
* export default definePlugin((nitroApp) => {
|
|
2381
|
-
* nitroApp.hooks.hook('mongocamp:ready', server => server.use(metrics()))
|
|
2382
|
-
* nitroApp.hooks.hook('mongocamp:document:delete', event => audit(event))
|
|
2383
|
-
* nitroApp.hooks.hook('mongocamp:document:beforeInsert', ({ documents, user }) => documents.forEach(d => d.createdBy = user.userId))
|
|
2384
|
-
* })
|
|
2385
|
-
*/
|
|
2386
|
-
type MongocampHooks = {
|
|
2387
|
-
'mongocamp:ready': (server: MongocampServer) => void | Promise<void>;
|
|
2388
|
-
} & {
|
|
2389
|
-
[N in EventName as `mongocamp:${N}`]: (event: MongocampEvent<N>) => void | Promise<void>;
|
|
2390
|
-
} & {
|
|
2391
|
-
[N in InterceptorName as `mongocamp:${N}`]: (payload: WriteInterceptorPayloads[N]) => void | Promise<void>;
|
|
2392
|
-
};
|
|
2393
|
-
/** The part of `hookable` (Nitro's `nitroApp.hooks`) the bridge needs. */
|
|
2394
|
-
interface HookSystem {
|
|
2395
|
-
callHook(name: string, ...args: unknown[]): unknown;
|
|
2396
|
-
}
|
|
2397
|
-
declare const HookPrefix = "mongocamp:";
|
|
2398
|
-
/** Calls `mongocamp:<event>` for every event of the server that has a hook listener; the returned function stops it. */
|
|
2399
|
-
declare function forwardEventsToHooks(server: Pick<MongocampServer, 'events'>, hooks: HookSystem): () => void;
|
|
2400
|
-
/**
|
|
2401
|
-
* Runs `mongocamp:document:beforeInsert`, ... of the hook system as interceptors of the writes (awaited, an error refuses the write); only
|
|
2402
|
-
* hooks with a listener cost anything. The returned function stops it.
|
|
2403
|
-
*/
|
|
2404
|
-
declare function forwardInterceptorsToHooks(server: Pick<MongocampServer, 'interceptors'>, hooks: HookSystem): () => void;
|
|
2405
|
-
/**
|
|
2406
|
-
* Connects a started server with the hooks of its host: forwards the events and the interceptors, and calls `mongocamp:ready` (awaited, so
|
|
2407
|
-
* features that the plugins switch on are active before the first request is answered).
|
|
2408
|
-
*/
|
|
2409
|
-
declare function connectHooks(server: MongocampServer, hooks: HookSystem): Promise<() => void>;
|
|
2410
|
-
|
|
2411
|
-
export { AuditCollection, BehaviourDefaults, CleanUpTokenJob, CleanUpTokenJobClass, CollectionRegistry, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, DefaultValidationMode, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, JobScheduler, LuceneQueryError, MongocampError, PaginationHeaders, SyncValidationLevel, TextMarker, WriteInterceptors, auditCollectionOf, auditRecords, bsonMarkerOptions, collections, combineScopes, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, decodeAny, defineMongocampCollection, documentToJson, ensureAuditIndexes, filterParameter, forwardEventsToHooks, forwardInterceptorsToHooks, guardedPaths, luceneQueryToFilter, luceneToFilter, metrics, notDeleted, ownedBy, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, purgeIndexName, readScope, requestFields, requestLogging, resolveBehaviours, restoreUpdate, sameValidator, stampInsert, stampReplace, stampUpdate, stringifyJson, stripDocument, stripUpdate, syncPurgeIndex, syncValidator, systemFields, toMongoJsonSchema, validatorOf, versionInDocument, versionInUpdate, withDeletedOf, withIncrement, withSystemFields, withVersion };
|
|
2412
|
-
export type { AuditOperation, AuditOptions, AuditRecord, BehaviourFlags, ConfigDefinition, ConfigKey, ConfigType, ConversionResult, ConvertOptions, DeclaredCollection, ErrorDescription, EventListener, EventName, EventTarget, ExtendedJsonMode, FetchOptions, HookSystem, InferDocument, InferDocumentInput, InterceptorBase, InterceptorName, InterceptorStage, InterceptorTarget, JobConfig, JobHandler, JobInformation, JobRun, LuceneQuery, MongocampCollectionDefinition, MongocampContext, MongocampEvent, MongocampEvents, MongocampFeature, MongocampHooks, MongocampLogger, MongocampRequestFields, MongocampServer, MongocampServerOptions, OwnerOptions, PaginationInfo, Paging, ReadOperation, ReadScope, RequestLog, ResolvedBehaviours, ScopeOptions, SoftDeleteOptions, SystemFields, TimestampsOptions, ValidationMode, ValidatorSyncAction, ValidatorSyncResult, VersionInfo, VersionedOptions, WriteInterceptor, WriteInterceptorPayloads, WriteStamp };
|
|
2810
|
+
export { AuditCollection, AuthService, AuthorizedUser, BehaviourDefaults, CleanUpTokenJob, CleanUpTokenJobClass, CollectionRegistry, ConfigKeys, ConfigPersistence, ConfigStore, ConfigurationError, DefaultRowsPerPage, DefaultValidationMode, DocumentService, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, InfoCache, InternalErrorMessage, JobScheduler, LuceneQueryError, MaxExpands, MongocampDatabase, MongocampError, MongocampMetrics, OwnIndexPrefix, PaginationHeaders, SyncValidationLevel, SystemUser, TextMarker, WriteInterceptors, auditCollectionOf, auditRecords, bsonMarkerOptions, collections, combineScopes, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, createServerCollection, decodeAny, defineMongocampCollection, documentToJson, ensureAuditIndexes, filterParameter, forwardEventsToHooks, forwardInterceptorsToHooks, guardedPaths, luceneQueryToFilter, luceneToFilter, metrics, notDeleted, ownedBy, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, purgeIndexName, readScope, refsOf, requestFields, requestLogging, resolveBehaviours, resolveIndexes, resolveRefs, restoreUpdate, sameValidator, stampInsert, stampReplace, stampUpdate, stringifyJson, stripDocument, stripUpdate, syncIndexes, syncPurgeIndex, syncValidator, systemFields, toErrorResponse, toMongoJsonSchema, validatorOf, versionInDocument, versionInUpdate, withDeletedOf, withIncrement, withSystemFields, withVersion };
|
|
2811
|
+
export type { AuditOperation, AuditOptions, AuditRecord, BehaviourFlags, ConfigDefinition, ConfigKey, ConfigType, ConversionResult, ConvertOptions, DeclaredCollection, ErrorDescription, ErrorResponseOptions, EventListener, EventName, EventTarget, ExpandedDocument, ExtendedJsonMode, FetchOptions, Grant, HookSystem, IndexDeclaration, IndexDirection, IndexOptions, IndexSyncResult, InferDocument, InferDocumentInput, InferRefs, InterceptorBase, InterceptorName, InterceptorStage, InterceptorTarget, JobConfig, JobHandler, JobInformation, JobRun, LuceneQuery, MongocampCollectionDefinition, MongocampContext, MongocampEvent, MongocampEvents, MongocampFeature, MongocampHooks, MongocampLogger, MongocampRequestFields, MongocampServer, MongocampServerOptions, OwnerOptions, PaginationInfo, Paging, ReadOperation, ReadScope, RefDeclaration, RefTargets, RequestLog, ResolvedBehaviours, ResolvedIndex, ResolvedRef, Role, ScopeOptions, ServerCollection, ServerCollectionOptions, ServerCollectionUser, ServerDocumentIdentity, ServerFindOptions, ServerPage, SoftDeleteOptions, SystemFields, SystemInfo, TimestampsOptions, UserInformation, ValidationIssue, ValidationMode, ValidatorSyncAction, ValidatorSyncResult, VersionInfo, VersionedOptions, WriteInterceptor, WriteInterceptorPayloads, WriteStamp };
|