kodzero-front-sdk-alfa 0.0.2
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/.eslintrc.cjs +13 -0
- package/.eslintrc.json +16 -0
- package/README.md +313 -0
- package/dist/Kodzero.d.ts +33 -0
- package/dist/Kodzero.js +22 -0
- package/dist/auth/base.d.ts +15 -0
- package/dist/auth/base.js +18 -0
- package/dist/auth/email.d.ts +23 -0
- package/dist/auth/email.js +70 -0
- package/dist/auth/index.d.ts +13 -0
- package/dist/auth/index.js +21 -0
- package/dist/auth/tokens.d.ts +10 -0
- package/dist/auth/tokens.js +22 -0
- package/dist/errors/KodzeroApiError.d.ts +7 -0
- package/dist/errors/KodzeroApiError.js +10 -0
- package/dist/errors/KodzeroValidationError.d.ts +5 -0
- package/dist/errors/KodzeroValidationError.js +8 -0
- package/dist/fetcher/InterceptorManager.d.ts +9 -0
- package/dist/fetcher/InterceptorManager.js +42 -0
- package/dist/fetcher/MiddlewareManager.d.ts +9 -0
- package/dist/fetcher/MiddlewareManager.js +42 -0
- package/dist/fetcher/index.d.ts +77 -0
- package/dist/fetcher/index.js +194 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +49 -0
- package/dist/model/BaseModel.d.ts +38 -0
- package/dist/model/BaseModel.js +119 -0
- package/dist/model/baseModelOptionsSchema.d.ts +2 -0
- package/dist/model/baseModelOptionsSchema.js +10 -0
- package/dist/model/configSchema.d.ts +0 -0
- package/dist/model/configSchema.js +1 -0
- package/dist/model/constants.d.ts +8 -0
- package/dist/model/constants.js +7 -0
- package/dist/model/createModel.d.ts +28 -0
- package/dist/model/createModel.js +159 -0
- package/dist/model/errors/KodzeroApiError.d.ts +7 -0
- package/dist/model/errors/KodzeroApiError.js +10 -0
- package/dist/model/index.d.ts +4 -0
- package/dist/model/index.js +4 -0
- package/dist/model/modelFactory.d.ts +50 -0
- package/dist/model/modelFactory.js +41 -0
- package/dist/model/modelSchema.d.ts +0 -0
- package/dist/model/modelSchema.js +1 -0
- package/dist/model/schemas/baseModel.d.ts +6 -0
- package/dist/model/schemas/baseModel.js +25 -0
- package/dist/model/schemas/baseModelOptionsSchema.d.ts +2 -0
- package/dist/model/schemas/baseModelOptionsSchema.js +10 -0
- package/dist/model/statics/getAll.d.ts +2 -0
- package/dist/model/statics/getAll.js +4 -0
- package/dist/model/utils/processUrl.d.ts +2 -0
- package/dist/model/utils/processUrl.js +7 -0
- package/dist/model/utils/validateApiResponse.d.ts +2 -0
- package/dist/model/utils/validateApiResponse.js +14 -0
- package/dist/schemas/baseAuth.d.ts +6 -0
- package/dist/schemas/baseAuth.js +18 -0
- package/dist/schemas/baseModel copy.d.ts +6 -0
- package/dist/schemas/baseModel copy.js +25 -0
- package/dist/schemas/baseModel.d.ts +6 -0
- package/dist/schemas/baseModel.js +25 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/dist/types/responses.d.ts +14 -0
- package/dist/types/responses.js +1 -0
- package/dist/utils/buildURL.d.ts +2 -0
- package/dist/utils/buildURL.js +7 -0
- package/dist/utils/buildURL_rename.d.ts +2 -0
- package/dist/utils/buildURL_rename.js +7 -0
- package/dist/utils/processUrl.d.ts +2 -0
- package/dist/utils/processUrl.js +7 -0
- package/dist/utils/validateApiResponse.d.ts +2 -0
- package/dist/utils/validateApiResponse.js +14 -0
- package/jest.config.ts +190 -0
- package/nodemon.json +4 -0
- package/package.json +29 -0
- package/src/Kodzero.ts +35 -0
- package/src/auth/base.ts +37 -0
- package/src/auth/email.ts +123 -0
- package/src/auth/index.ts +43 -0
- package/src/auth/tokens.ts +49 -0
- package/src/errors/KodzeroApiError.ts +17 -0
- package/src/errors/KodzeroValidationError.ts +12 -0
- package/src/model/BaseModel.ts +210 -0
- package/src/model/constants.ts +7 -0
- package/src/model/createModel.ts +237 -0
- package/src/model/index.ts +12 -0
- package/src/schemas/baseAuth.ts +28 -0
- package/src/schemas/baseModel.ts +35 -0
- package/src/tsconfig.json +103 -0
- package/src/types/module.d.ts +2 -0
- package/src/types/responses.ts +14 -0
- package/src/utils/buildURL_rename.ts +8 -0
- package/src/utils/validateApiResponse.ts +17 -0
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import Schema from "validno";
|
|
2
|
+
import FluidFetch from "fluid-fetch";
|
|
3
|
+
|
|
4
|
+
import constants from "./constants.js";
|
|
5
|
+
import validateApiResponse from "../utils/validateApiResponse.js";
|
|
6
|
+
import BaseModelSchema from "../schemas/baseModel.js";
|
|
7
|
+
import buildURL from "../utils/buildURL_rename.js";
|
|
8
|
+
|
|
9
|
+
export interface ModelOptions {
|
|
10
|
+
host: string
|
|
11
|
+
collection: string
|
|
12
|
+
schema?: typeof Schema
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Base model constructor that expose main methods to work with user-created model
|
|
17
|
+
*/
|
|
18
|
+
class BaseModel<T extends { _id?: string }> {
|
|
19
|
+
host: string
|
|
20
|
+
collection: string
|
|
21
|
+
modelData: T = {} as T
|
|
22
|
+
schema?: typeof Schema
|
|
23
|
+
api: typeof FluidFetch
|
|
24
|
+
|
|
25
|
+
id: string | null;
|
|
26
|
+
|
|
27
|
+
static url: string
|
|
28
|
+
static collection: string
|
|
29
|
+
static api: typeof FluidFetch
|
|
30
|
+
|
|
31
|
+
constructor(options: ModelOptions, api: typeof FluidFetch) {
|
|
32
|
+
BaseModelSchema.validateOrThrow(options);
|
|
33
|
+
|
|
34
|
+
this.host = options.host
|
|
35
|
+
this.collection = options.collection
|
|
36
|
+
this.schema = options.schema
|
|
37
|
+
this.api = api
|
|
38
|
+
this.id = null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Private
|
|
43
|
+
* Setter for this.id
|
|
44
|
+
*/
|
|
45
|
+
_setId = (id: string | null) => {
|
|
46
|
+
this.id = id
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Private
|
|
51
|
+
* Setter for this.modelData. Also sets this.id if it is present
|
|
52
|
+
*/
|
|
53
|
+
_setModelData = (data: T) => {
|
|
54
|
+
this.modelData = data;
|
|
55
|
+
this._setId(data?._id || null);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Private
|
|
60
|
+
* Links to API error handler
|
|
61
|
+
*/
|
|
62
|
+
_handleApiError(response: Response) {
|
|
63
|
+
return validateApiResponse(response)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Getter for model's data (this.modelData)
|
|
68
|
+
*/
|
|
69
|
+
data(): T {
|
|
70
|
+
return this.modelData
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Private
|
|
75
|
+
* Getter for model's data (this.modelData) excluding "_id" field
|
|
76
|
+
* Used to
|
|
77
|
+
*/
|
|
78
|
+
_dataWithoutId(): Omit<T, "_id"> | {} {
|
|
79
|
+
if (typeof this.modelData === 'object' && this.modelData !== null && '_id' in this.modelData) {
|
|
80
|
+
const { _id, ...dataWithoutId } = this.modelData as T;
|
|
81
|
+
return dataWithoutId;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return this.modelData;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Private
|
|
89
|
+
* Sets nested keys of this.modelData by the path
|
|
90
|
+
* Path example: 'key.level2.level3'
|
|
91
|
+
*/
|
|
92
|
+
_setNested(key: string, value: any) {
|
|
93
|
+
const keys = key.split('.');
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
let obj = this.modelData;
|
|
97
|
+
while (keys.length > 1) {
|
|
98
|
+
const k = keys.shift()!;
|
|
99
|
+
// @ts-ignore
|
|
100
|
+
if (!(k in obj)) obj[k] = {};
|
|
101
|
+
// @ts-ignore
|
|
102
|
+
obj = obj[k];
|
|
103
|
+
}
|
|
104
|
+
// @ts-ignore
|
|
105
|
+
obj[keys[0]] = value;
|
|
106
|
+
|
|
107
|
+
return this.modelData
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Setter for model's data (this.modelData)
|
|
112
|
+
*/
|
|
113
|
+
set(data: Record<string, any> | string, value?: any) {
|
|
114
|
+
if (typeof data === 'string' && value !== undefined) {
|
|
115
|
+
this._setNested(data, value);
|
|
116
|
+
} else if (typeof data === 'object') {
|
|
117
|
+
Object.entries(data).forEach(([key, value]) => {
|
|
118
|
+
this._setNested(key, value);
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return this.modelData;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Validates model's data against it's schema
|
|
127
|
+
*/
|
|
128
|
+
validate(): {ok: boolean, errors: string[], joinErrors: () => string} {
|
|
129
|
+
const schema = this.schema;
|
|
130
|
+
|
|
131
|
+
if (!schema) {
|
|
132
|
+
throw new Error(constants.NoSchema);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const keysToValidate = Object.keys(this.schema.definition).filter(k => k !== '_id')
|
|
136
|
+
const validationResult = schema.validate(this._dataWithoutId(), keysToValidate);
|
|
137
|
+
|
|
138
|
+
return validationResult
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Sends patch request to update document data by it's _id
|
|
143
|
+
*/
|
|
144
|
+
async update(): Promise<T> {
|
|
145
|
+
if (!this.id) {
|
|
146
|
+
throw new Error(constants.RequiresId);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const updateUrl = buildURL(this.host, this.collection, this.id)
|
|
150
|
+
|
|
151
|
+
const response = await this.api.patch(updateUrl, this._dataWithoutId())
|
|
152
|
+
.headers({ 'Content-Type': 'application/json' });
|
|
153
|
+
|
|
154
|
+
await this._handleApiError(response);
|
|
155
|
+
const json = await response.json();
|
|
156
|
+
|
|
157
|
+
this._setModelData(json.result);
|
|
158
|
+
|
|
159
|
+
return this.modelData
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Sends delete request to delete document by it's _id
|
|
164
|
+
*/
|
|
165
|
+
async delete(): Promise<boolean> {
|
|
166
|
+
if (!this.id) {
|
|
167
|
+
throw new Error(constants.RequiresId);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const deleteUrl = buildURL(this.host, this.collection, this.id);
|
|
171
|
+
|
|
172
|
+
const response = await this.api.delete(deleteUrl);
|
|
173
|
+
await this._handleApiError(response);
|
|
174
|
+
|
|
175
|
+
this._setId(null);
|
|
176
|
+
this.modelData = {} as T;
|
|
177
|
+
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Sends post request to insert document into the collection
|
|
183
|
+
*/
|
|
184
|
+
async create(): Promise<T> {
|
|
185
|
+
const createUrl = buildURL(this.host, this.collection)
|
|
186
|
+
|
|
187
|
+
const response = await this.api.post(createUrl, this._dataWithoutId())
|
|
188
|
+
.headers({ 'Content-Type': 'application/json' });
|
|
189
|
+
|
|
190
|
+
await this._handleApiError(response);
|
|
191
|
+
const json = await response.json();
|
|
192
|
+
|
|
193
|
+
this._setModelData(json.result);
|
|
194
|
+
|
|
195
|
+
return this.modelData
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Updates document or inserts it depending on presense of _id (this.id)
|
|
200
|
+
*/
|
|
201
|
+
async save(): Promise<T> {
|
|
202
|
+
if (this.id) {
|
|
203
|
+
return this.update();
|
|
204
|
+
} else {
|
|
205
|
+
return this.create();
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export default BaseModel
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export default {
|
|
2
|
+
NoSchema: 'No schema defined for validation',
|
|
3
|
+
RequiresId: 'Method requires model id',
|
|
4
|
+
DataTypeNotArray: 'Data must be a non-empty array',
|
|
5
|
+
RequiresIdsArray: 'Method requires array of ids',
|
|
6
|
+
DistinctRequiresFieldsArray: 'Distinct methods requires array of fields'
|
|
7
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import FluidFetch from 'fluid-fetch'
|
|
2
|
+
import BaseModel, { ModelOptions } from './BaseModel.js'
|
|
3
|
+
import {KzResponseFindMany } from '../types/responses.js'
|
|
4
|
+
import validateApiResponse from '../utils/validateApiResponse.js'
|
|
5
|
+
import buildURL from '../utils/buildURL_rename.js'
|
|
6
|
+
import constants from './constants.js'
|
|
7
|
+
|
|
8
|
+
export interface FindManyOptions {
|
|
9
|
+
page: number
|
|
10
|
+
perPage: number
|
|
11
|
+
search?: string
|
|
12
|
+
sort?: string
|
|
13
|
+
fields?: string[]
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Creates custom model with the specified schema, API options, etc.
|
|
18
|
+
*/
|
|
19
|
+
const createModel = <
|
|
20
|
+
T extends { _id?: string },
|
|
21
|
+
M = {}
|
|
22
|
+
>(options: ModelOptions, api: typeof FluidFetch) => {
|
|
23
|
+
const Model = class extends BaseModel<T> {
|
|
24
|
+
static host = options.host
|
|
25
|
+
static collection = options.collection
|
|
26
|
+
static api = api
|
|
27
|
+
|
|
28
|
+
static async _handleApiError(response: Response) {
|
|
29
|
+
return validateApiResponse(response)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// ** Model methods **
|
|
33
|
+
static async get(id: string): Promise<InstanceType<typeof Model>> {
|
|
34
|
+
if (!id) throw new Error(constants.RequiresId)
|
|
35
|
+
|
|
36
|
+
const getUrl = buildURL(Model.host, Model.collection, id)
|
|
37
|
+
|
|
38
|
+
const response = await Model.api.get(getUrl);
|
|
39
|
+
await Model._handleApiError(response);
|
|
40
|
+
|
|
41
|
+
const json = await response.json();
|
|
42
|
+
|
|
43
|
+
return new Model(json.result);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Adds custom method to Model
|
|
48
|
+
*
|
|
49
|
+
* TS support: pass interfaces for both data and custom methods:
|
|
50
|
+
* Example:
|
|
51
|
+
* interface Dog { name: string }
|
|
52
|
+
* interface DogMethods { greet: () => `Woof! ${this.data().name}`}
|
|
53
|
+
* "createModel<Dog, DogMethods>(...)"
|
|
54
|
+
*/
|
|
55
|
+
static registerMethod<K extends keyof M>(name: K, fn: M[K]) {
|
|
56
|
+
(Model.prototype as any)[name] = fn;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// ** Collection methods **
|
|
60
|
+
static async find(id: string): Promise<T> {
|
|
61
|
+
if (!id) throw new Error(constants.RequiresId);
|
|
62
|
+
|
|
63
|
+
const getUrl = buildURL(Model.host, Model.collection, id)
|
|
64
|
+
|
|
65
|
+
const response = await Model.api.get(getUrl);
|
|
66
|
+
await Model._handleApiError(response);
|
|
67
|
+
|
|
68
|
+
const data = await response.json();
|
|
69
|
+
return data.result;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
static async findMany(options?: FindManyOptions | {}): Promise<T[]> {
|
|
73
|
+
const getUrl = buildURL(Model.host, Model.collection)
|
|
74
|
+
|
|
75
|
+
const params = {...options} as Record<string, any>;
|
|
76
|
+
|
|
77
|
+
const response = await Model.api.get(getUrl).params(params);
|
|
78
|
+
await Model._handleApiError(response);
|
|
79
|
+
|
|
80
|
+
const data: KzResponseFindMany<T> = await response.json();
|
|
81
|
+
return data.result.found;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
static async create(data: T): Promise<T> {
|
|
85
|
+
const createUrl = buildURL(Model.host, Model.collection)
|
|
86
|
+
const {_id, ...dataWithoutId} = data as T & {_id?: string};
|
|
87
|
+
|
|
88
|
+
const response = await Model.api.post(createUrl)
|
|
89
|
+
.body(dataWithoutId)
|
|
90
|
+
.headers({
|
|
91
|
+
'Content-Type': 'application/json'
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
await Model._handleApiError(response);
|
|
95
|
+
|
|
96
|
+
const json = await response.json();
|
|
97
|
+
return json.result
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
static async createMany(records: T[]): Promise<T[]> {
|
|
101
|
+
if (!records || !Array.isArray(records) || !records.length) {
|
|
102
|
+
throw new Error(constants.DataTypeNotArray)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const createUrl = buildURL(Model.host, Model.collection) + '/batch'
|
|
106
|
+
|
|
107
|
+
const dataWithoutId = records.map(item => {
|
|
108
|
+
const {_id, ...rest} = item as T & {_id?: string};
|
|
109
|
+
return rest;
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
const response = await Model.api.post(createUrl)
|
|
113
|
+
.body(dataWithoutId)
|
|
114
|
+
.headers({
|
|
115
|
+
'Content-Type': 'application/json'
|
|
116
|
+
})
|
|
117
|
+
await Model._handleApiError(response);
|
|
118
|
+
|
|
119
|
+
const json = await response.json();
|
|
120
|
+
return json.result
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
static async update(id: string, data: Partial<T>): Promise<T> {
|
|
124
|
+
if (!id) {
|
|
125
|
+
throw new Error(constants.RequiresId);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const updateUrl = buildURL(Model.host, Model.collection, id)
|
|
129
|
+
const {_id, ...dataWithoutId} = data as Partial<T> & {_id?: string};
|
|
130
|
+
const response = await Model.api.patch(updateUrl)
|
|
131
|
+
.body(dataWithoutId)
|
|
132
|
+
.headers({ 'Content-Type': 'application/json' });
|
|
133
|
+
|
|
134
|
+
await Model._handleApiError(response);
|
|
135
|
+
const json = await response.json();
|
|
136
|
+
|
|
137
|
+
return json.result;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
static async updateMany(updates: Partial<T>[]): Promise<T[]> {
|
|
141
|
+
if (!updates || !Array.isArray(updates) || updates.length === 0) {
|
|
142
|
+
throw new Error(constants.DataTypeNotArray);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (updates.some(update => !update._id)) {
|
|
146
|
+
throw new Error("All updates must have an _id");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const updateUrl = buildURL(Model.host, Model.collection) + '/batch'
|
|
150
|
+
|
|
151
|
+
const response = await Model.api.patch(updateUrl)
|
|
152
|
+
.body(updates)
|
|
153
|
+
.headers({ 'Content-Type': 'application/json' });
|
|
154
|
+
|
|
155
|
+
await Model._handleApiError(response);
|
|
156
|
+
const json = await response.json();
|
|
157
|
+
|
|
158
|
+
return json.result;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
static async delete(id: string): Promise<boolean> {
|
|
162
|
+
if (!id) throw new Error(constants.RequiresId);
|
|
163
|
+
|
|
164
|
+
const deleteUrl = buildURL(Model.host, Model.collection, id)
|
|
165
|
+
|
|
166
|
+
const response = await Model.api.delete(deleteUrl);
|
|
167
|
+
await Model._handleApiError(response);
|
|
168
|
+
|
|
169
|
+
const json = await response.json();
|
|
170
|
+
return json.result;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
static async deleteMany(ids: string[]): Promise<Record<string, boolean>> {
|
|
174
|
+
if (!ids || ids.length === 0) {
|
|
175
|
+
throw new Error(constants.RequiresIdsArray);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const deleteUrl = buildURL(Model.host, Model.collection) + '/batch'
|
|
179
|
+
|
|
180
|
+
const response = await Model.api.delete(deleteUrl)
|
|
181
|
+
.body({ ids })
|
|
182
|
+
.headers({ 'Content-Type': 'application/json' });
|
|
183
|
+
|
|
184
|
+
await Model._handleApiError(response);
|
|
185
|
+
|
|
186
|
+
const json = await response.json();
|
|
187
|
+
return json.result;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
static async distinct(fields: string[], filter?: Record<string, any>): Promise<string[]> {
|
|
191
|
+
if (!fields || fields.length === 0) {
|
|
192
|
+
throw new Error(constants.DistinctRequiresFieldsArray);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const distinctUrl = buildURL(Model.host, Model.collection, 'distinct')
|
|
196
|
+
|
|
197
|
+
const response = await Model.api.post(distinctUrl)
|
|
198
|
+
.params({ fields: fields.join(','), filter: filter ? JSON.stringify(filter) : undefined })
|
|
199
|
+
.headers({ 'Content-Type': 'application/json' });
|
|
200
|
+
|
|
201
|
+
await Model._handleApiError(response);
|
|
202
|
+
|
|
203
|
+
const json = await response.json();
|
|
204
|
+
return json.result;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
constructor(data: T) {
|
|
208
|
+
super(options, api)
|
|
209
|
+
|
|
210
|
+
this.modelData = {...data, _id: null}
|
|
211
|
+
this.id = null;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Return type: ModelConstructor<T, M>
|
|
216
|
+
type ModelInstance = BaseModel<T> & M;
|
|
217
|
+
type Model = {
|
|
218
|
+
new(data: T): ModelInstance;
|
|
219
|
+
get(id: string): Promise<ModelInstance>;
|
|
220
|
+
registerMethod<K extends keyof M>(name: K, fn: M[K]): void;
|
|
221
|
+
find(id: string): Promise<T>;
|
|
222
|
+
findMany(options?: FindManyOptions | {}): Promise<T[]>;
|
|
223
|
+
create(data: T): Promise<T>;
|
|
224
|
+
createMany(data: T[]): Promise<T[]>;
|
|
225
|
+
update(id: string, data: Partial<T>): Promise<T>;
|
|
226
|
+
updateMany(updates: Partial<T>[]): Promise<T[]>;
|
|
227
|
+
delete(id: string): Promise<boolean>;
|
|
228
|
+
deleteMany(ids: string[]): Promise<Record<string, boolean>>;
|
|
229
|
+
distinct(fields: string[], filter?: Record<string, any>): Promise<string[]>;
|
|
230
|
+
host: string;
|
|
231
|
+
collection: string;
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
return Model as unknown as Model;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export default createModel
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import Schema from 'validno'
|
|
2
|
+
import KodzeroValidationError from '../errors/KodzeroValidationError.js';
|
|
3
|
+
|
|
4
|
+
class BaseAuthSchema {
|
|
5
|
+
// Validation schema for BaseAuth class constructor options
|
|
6
|
+
static schema = new Schema({
|
|
7
|
+
host: {
|
|
8
|
+
type: String
|
|
9
|
+
}
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
static validate = (options: Record<string, any>) => BaseAuthSchema.schema.validate(options);
|
|
13
|
+
|
|
14
|
+
static validateOrThrow = (options: Record<string, any>) => {
|
|
15
|
+
const validation = BaseAuthSchema.schema.validate(options);
|
|
16
|
+
|
|
17
|
+
if (!validation.ok) {
|
|
18
|
+
throw new KodzeroValidationError(
|
|
19
|
+
'Invalid auth options: ' + validation.failed.join(', '),
|
|
20
|
+
validation.errors
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return true
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export default BaseAuthSchema;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import Schema from 'validno'
|
|
2
|
+
import KodzeroValidationError from '../errors/KodzeroValidationError.js';
|
|
3
|
+
|
|
4
|
+
class BaseModelSchema {
|
|
5
|
+
// Validation schema for BaseModel class constructor options
|
|
6
|
+
static schema = new Schema({
|
|
7
|
+
host: {
|
|
8
|
+
type: String
|
|
9
|
+
},
|
|
10
|
+
collection: {
|
|
11
|
+
type: String
|
|
12
|
+
},
|
|
13
|
+
schema: {
|
|
14
|
+
type: Schema,
|
|
15
|
+
required: false
|
|
16
|
+
}
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
static validate = (options: Record<string, any>) => BaseModelSchema.schema.validate(options);
|
|
20
|
+
|
|
21
|
+
static validateOrThrow = (options: Record<string, any>) => {
|
|
22
|
+
const validation = BaseModelSchema.schema.validate(options);
|
|
23
|
+
|
|
24
|
+
if (!validation.ok) {
|
|
25
|
+
throw new KodzeroValidationError(
|
|
26
|
+
'Invalid model options: ' + validation.failed.join(', '),
|
|
27
|
+
validation.errors
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return true
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export default BaseModelSchema;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
/* Visit https://aka.ms/tsconfig to read more about this file */
|
|
4
|
+
|
|
5
|
+
/* Projects */
|
|
6
|
+
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
|
7
|
+
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
|
8
|
+
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
|
9
|
+
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
|
10
|
+
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
|
11
|
+
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
|
12
|
+
|
|
13
|
+
/* Language and Environment */
|
|
14
|
+
"target": "ES2017", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
|
15
|
+
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
|
16
|
+
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
|
17
|
+
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
|
18
|
+
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
|
19
|
+
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
|
20
|
+
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
|
21
|
+
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
|
22
|
+
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
|
23
|
+
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
|
24
|
+
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
|
25
|
+
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
|
26
|
+
|
|
27
|
+
/* Modules */
|
|
28
|
+
"module": "ES2022", /* Specify what module code is generated. */
|
|
29
|
+
"rootDir": "../src/", /* Specify the root folder within your source files. */
|
|
30
|
+
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
|
31
|
+
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
|
32
|
+
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
|
33
|
+
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
|
34
|
+
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
|
35
|
+
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
|
36
|
+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
|
37
|
+
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
|
38
|
+
// "resolveJsonModule": true, /* Enable importing .json files. */
|
|
39
|
+
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
|
40
|
+
|
|
41
|
+
/* JavaScript Support */
|
|
42
|
+
"allowJs": false, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
|
43
|
+
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
|
44
|
+
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
|
45
|
+
|
|
46
|
+
/* Emit */
|
|
47
|
+
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
|
48
|
+
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
|
49
|
+
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
|
50
|
+
"sourceMap": false, /* Create source map files for emitted JavaScript files. */
|
|
51
|
+
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
|
52
|
+
"outDir": "../dist/", /* Specify an output folder for all emitted files. */
|
|
53
|
+
"removeComments": true, /* Disable emitting comments. */
|
|
54
|
+
// "noEmit": true, /* Disable emitting files from a compilation. */
|
|
55
|
+
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
|
56
|
+
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
|
57
|
+
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
|
58
|
+
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
|
59
|
+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
|
60
|
+
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
|
61
|
+
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
|
62
|
+
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
|
63
|
+
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
|
64
|
+
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
|
65
|
+
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
|
66
|
+
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
|
67
|
+
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
|
68
|
+
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
|
69
|
+
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
|
70
|
+
|
|
71
|
+
/* Interop Constraints */
|
|
72
|
+
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
|
73
|
+
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
|
74
|
+
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
|
75
|
+
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
|
76
|
+
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
|
77
|
+
|
|
78
|
+
/* Type Checking */
|
|
79
|
+
"strict": true, /* Enable all strict type-checking options. */
|
|
80
|
+
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
|
81
|
+
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
|
82
|
+
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
|
83
|
+
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
|
84
|
+
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
|
85
|
+
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
|
86
|
+
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
|
87
|
+
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
|
88
|
+
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
|
89
|
+
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
|
90
|
+
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
|
91
|
+
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
|
92
|
+
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
|
93
|
+
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
|
94
|
+
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
|
95
|
+
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
|
96
|
+
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
|
97
|
+
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
|
98
|
+
|
|
99
|
+
/* Completeness */
|
|
100
|
+
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
|
101
|
+
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
|
102
|
+
}
|
|
103
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface KzResponse<T = any> {
|
|
2
|
+
ok: boolean
|
|
3
|
+
result: T
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export interface KzResponseFindMany<T = any> extends KzResponse<{
|
|
7
|
+
skip: number,
|
|
8
|
+
limit: number,
|
|
9
|
+
page: number,
|
|
10
|
+
total: number,
|
|
11
|
+
totalPages: number,
|
|
12
|
+
left: number,
|
|
13
|
+
found: T[],
|
|
14
|
+
}> {}
|