kodzero-front-sdk-alfa 0.0.4 → 0.0.6

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.
Files changed (78) hide show
  1. package/README.md +6 -6
  2. package/dist/Kodzero.d.ts +1 -0
  3. package/dist/Kodzero.js +7 -3
  4. package/dist/__mocks__/fluid-fetch.d.ts +1 -0
  5. package/dist/__mocks__/fluid-fetch.js +23 -0
  6. package/dist/__mocks__/validno.d.ts +5 -0
  7. package/dist/__mocks__/validno.js +9 -0
  8. package/dist/auth/base.d.ts +3 -3
  9. package/dist/auth/base.js +8 -5
  10. package/dist/auth/email.d.ts +4 -4
  11. package/dist/auth/email.js +62 -60
  12. package/dist/auth/index.js +6 -3
  13. package/dist/auth/tokens.js +2 -0
  14. package/dist/errors/KodzeroApiError.js +3 -0
  15. package/dist/errors/KodzeroValidationError.js +1 -0
  16. package/dist/index.d.ts +2 -1
  17. package/dist/index.js +1 -48
  18. package/dist/model/BaseModel.d.ts +2 -2
  19. package/dist/model/BaseModel.js +25 -28
  20. package/dist/model/PaginatedResult.d.ts +28 -0
  21. package/dist/model/PaginatedResult.js +49 -0
  22. package/dist/model/createModel.d.ts +3 -1
  23. package/dist/model/createModel.js +145 -147
  24. package/dist/schemas/baseAuth.js +13 -13
  25. package/dist/schemas/baseModel.js +20 -20
  26. package/dist/tsconfig.tsbuildinfo +1 -1
  27. package/dist/utils/buildURL.js +3 -1
  28. package/dist/utils/validateApiResponse.js +1 -1
  29. package/jest.config.ts +23 -19
  30. package/package.json +6 -5
  31. package/src/__mocks__/fluid-fetch.ts +35 -0
  32. package/src/__mocks__/validno.ts +12 -0
  33. package/src/__tests__/Kodzero.test.ts +9 -0
  34. package/src/__tests__/utils/buildURL.test.ts +18 -0
  35. package/src/auth/base.ts +3 -3
  36. package/src/auth/email.ts +11 -11
  37. package/src/auth/index.ts +3 -3
  38. package/src/index.ts +3 -0
  39. package/src/model/BaseModel.ts +10 -12
  40. package/src/model/PaginatedResult.ts +81 -0
  41. package/src/model/createModel.ts +39 -15
  42. package/src/schemas/baseAuth.ts +2 -1
  43. package/src/schemas/baseModel.ts +1 -1
  44. package/src/tsconfig.json +9 -8
  45. package/src/utils/buildURL.ts +2 -1
  46. package/dist/fetcher/InterceptorManager.d.ts +0 -9
  47. package/dist/fetcher/InterceptorManager.js +0 -42
  48. package/dist/fetcher/MiddlewareManager.d.ts +0 -9
  49. package/dist/fetcher/MiddlewareManager.js +0 -42
  50. package/dist/fetcher/index.d.ts +0 -77
  51. package/dist/fetcher/index.js +0 -194
  52. package/dist/model/baseModelOptionsSchema.d.ts +0 -2
  53. package/dist/model/baseModelOptionsSchema.js +0 -10
  54. package/dist/model/configSchema.d.ts +0 -0
  55. package/dist/model/configSchema.js +0 -1
  56. package/dist/model/errors/KodzeroApiError.d.ts +0 -7
  57. package/dist/model/errors/KodzeroApiError.js +0 -10
  58. package/dist/model/modelFactory.d.ts +0 -50
  59. package/dist/model/modelFactory.js +0 -41
  60. package/dist/model/modelSchema.d.ts +0 -0
  61. package/dist/model/modelSchema.js +0 -1
  62. package/dist/model/schemas/baseModel.d.ts +0 -6
  63. package/dist/model/schemas/baseModel.js +0 -25
  64. package/dist/model/schemas/baseModelOptionsSchema.d.ts +0 -2
  65. package/dist/model/schemas/baseModelOptionsSchema.js +0 -10
  66. package/dist/model/statics/getAll.d.ts +0 -2
  67. package/dist/model/statics/getAll.js +0 -4
  68. package/dist/model/utils/processUrl.d.ts +0 -2
  69. package/dist/model/utils/processUrl.js +0 -7
  70. package/dist/model/utils/validateApiResponse.d.ts +0 -2
  71. package/dist/model/utils/validateApiResponse.js +0 -14
  72. package/dist/schemas/baseModel copy.d.ts +0 -6
  73. package/dist/schemas/baseModel copy.js +0 -25
  74. package/dist/utils/buildURL_rename.d.ts +0 -2
  75. package/dist/utils/buildURL_rename.js +0 -7
  76. package/dist/utils/processUrl.d.ts +0 -2
  77. package/dist/utils/processUrl.js +0 -7
  78. /package/{.eslintrc.cjs → eslintrc.cjs} +0 -0
package/README.md CHANGED
@@ -18,14 +18,14 @@ const kodzero = new Kodzero({
18
18
  host: 'https://api.your-backend.com'
19
19
  });
20
20
 
21
- // Sign up a new user
22
- const signupResult = await kodzero.auth.signup({
21
+ // New user registration
22
+ const registerResult = await kodzero.auth.register({
23
23
  email: 'user@example.com',
24
24
  password: 'secure_password'
25
25
  });
26
26
 
27
- // Sign in
28
- const signinResult = await kodzero.auth.signin({
27
+ // Login
28
+ const loginResult = await kodzero.auth.login({
29
29
  email: 'user@example.com',
30
30
  password: 'secure_password'
31
31
  });
@@ -36,8 +36,8 @@ const verified = await kodzero.auth.verify();
36
36
  // Refresh the token
37
37
  const refreshed = await kodzero.auth.refresh();
38
38
 
39
- // Sign out
40
- await kodzero.auth.signout();
39
+ // Logout
40
+ await kodzero.auth.logout();
41
41
 
42
42
  // Manually set tokens (useful for persisting sessions)
43
43
  kodzero.auth.setTokens('access_token', 'refresh_token');
package/dist/Kodzero.d.ts CHANGED
@@ -19,6 +19,7 @@ declare class Kodzero {
19
19
  registerMethod<K extends keyof M>(name: K, fn: M[K]): void;
20
20
  find(id: string): Promise<T>;
21
21
  findMany(options?: import("./model/createModel.js").FindManyOptions | {}): Promise<T[]>;
22
+ findManyPaginated(options?: import("./model/createModel.js").FindManyOptions | {}, page?: number, perPage?: number): Promise<import("./model/PaginatedResult.js").default<T>>;
22
23
  create(data: T): Promise<T>;
23
24
  createMany(data: T[]): Promise<T[]>;
24
25
  update(id: string, data: Partial<T>): Promise<T>;
package/dist/Kodzero.js CHANGED
@@ -3,10 +3,11 @@ import KodzeroAuth from "./auth/index.js";
3
3
  import createModel from "./model/createModel.js";
4
4
  import TokensManagerClass from "./auth/tokens.js";
5
5
  class Kodzero {
6
+ host;
7
+ auth;
8
+ tokensManager;
9
+ api;
6
10
  constructor(options) {
7
- this.createModel = (options) => {
8
- return createModel(Object.assign(Object.assign({}, options), { host: this.host }), this.api);
9
- };
10
11
  this.tokensManager = new TokensManagerClass('', '');
11
12
  this.host = options.host;
12
13
  this.api = new FluidFetch();
@@ -18,5 +19,8 @@ class Kodzero {
18
19
  return req;
19
20
  });
20
21
  }
22
+ createModel = (options) => {
23
+ return createModel({ ...options, host: this.host }, this.api);
24
+ };
21
25
  }
22
26
  export default Kodzero;
@@ -0,0 +1 @@
1
+ export default function FluidFetch(this: any, options?: {}): void;
@@ -0,0 +1,23 @@
1
+ export default function FluidFetch(options = {}) {
2
+ this.options = options;
3
+ const middlewares = {
4
+ request: {
5
+ use: jest.fn()
6
+ },
7
+ response: {
8
+ use: jest.fn()
9
+ }
10
+ };
11
+ const request = jest.fn().mockImplementation(() => Promise.resolve({
12
+ data: {},
13
+ headers: {},
14
+ status: 200
15
+ }));
16
+ this.middlewares = middlewares;
17
+ this.request = request;
18
+ this.api = {
19
+ middlewares,
20
+ request
21
+ };
22
+ }
23
+ FluidFetch.prototype.constructor = FluidFetch;
@@ -0,0 +1,5 @@
1
+ export default function Schema(): {
2
+ validate: () => {
3
+ ok: boolean;
4
+ };
5
+ };
@@ -0,0 +1,9 @@
1
+ export default function Schema() {
2
+ return {
3
+ validate: () => {
4
+ return {
5
+ ok: true
6
+ };
7
+ },
8
+ };
9
+ }
@@ -7,10 +7,10 @@ declare class KodzeroAuthBase {
7
7
  tokensManager: TokensManagerClass;
8
8
  constructor(options: AuthOptions, api: typeof FluidFetch, tokensManager: TokensManagerClass);
9
9
  _handleApiError(response: Response): Promise<void>;
10
- signin: (...args: any[]) => Promise<any> | void;
11
- signup: (...args: any[]) => Promise<any> | void;
10
+ login: (...args: any[]) => Promise<any> | void;
11
+ register: (...args: any[]) => Promise<any> | void;
12
12
  refresh: (...args: any[]) => Promise<any> | void;
13
- signout: (...args: any[]) => Promise<any> | void;
13
+ logout: (...args: any[]) => Promise<any> | void;
14
14
  verify: (...args: any[]) => Promise<any> | void;
15
15
  }
16
16
  export default KodzeroAuthBase;
package/dist/auth/base.js CHANGED
@@ -1,12 +1,10 @@
1
1
  import BaseAuthSchema from "../schemas/baseAuth.js";
2
2
  import validateApiResponse from "../utils/validateApiResponse.js";
3
3
  class KodzeroAuthBase {
4
+ host;
5
+ api;
6
+ tokensManager;
4
7
  constructor(options, api, tokensManager) {
5
- this.signin = (...args) => { };
6
- this.signup = (...args) => { };
7
- this.refresh = (...args) => { };
8
- this.signout = (...args) => { };
9
- this.verify = (...args) => { };
10
8
  BaseAuthSchema.validateOrThrow(options);
11
9
  this.host = options.host;
12
10
  this.api = api;
@@ -15,5 +13,10 @@ class KodzeroAuthBase {
15
13
  _handleApiError(response) {
16
14
  return validateApiResponse(response);
17
15
  }
16
+ login = (...args) => { };
17
+ register = (...args) => { };
18
+ refresh = (...args) => { };
19
+ logout = (...args) => { };
20
+ verify = (...args) => { };
18
21
  }
19
22
  export default KodzeroAuthBase;
@@ -2,7 +2,7 @@ import FluidFetch from "fluid-fetch";
2
2
  import { AuthOptions } from "./index.js";
3
3
  import KodzeroAuthBase from "./base.js";
4
4
  import TokensManagerClass from "./tokens.js";
5
- interface KodzeroAuthEmailSignin {
5
+ interface KodzeroAuthEmailLogin {
6
6
  email: string;
7
7
  password: string;
8
8
  }
@@ -11,13 +11,13 @@ declare class KodzeroAuthEmail extends KodzeroAuthBase {
11
11
  collection: "auth/password";
12
12
  constructor(options: AuthOptions, api: typeof FluidFetch, tokensManager: TokensManagerClass);
13
13
  _setTokens: (access: string, refresh?: string) => void;
14
- signin: (input: KodzeroAuthEmailSignin) => Promise<{
14
+ login: (input: KodzeroAuthEmailLogin) => Promise<{
15
15
  access: string;
16
16
  refresh: string;
17
17
  }>;
18
- signup: (userData: Record<string, string>) => Promise<Record<string, any>>;
18
+ register: (userData: Record<string, string>) => Promise<Record<string, any>>;
19
19
  verify: () => Promise<any>;
20
20
  refresh: () => Promise<any>;
21
- signout: () => Promise<any>;
21
+ logout: () => Promise<any>;
22
22
  }
23
23
  export default KodzeroAuthEmail;
@@ -1,70 +1,72 @@
1
1
  import buildURL from "../utils/buildURL.js";
2
2
  import KodzeroAuthBase from "./base.js";
3
3
  class KodzeroAuthEmail extends KodzeroAuthBase {
4
+ tokensManager;
5
+ collection;
4
6
  constructor(options, api, tokensManager) {
5
7
  super(options, api, tokensManager);
6
- this._setTokens = (access, refresh) => {
7
- this.tokensManager.setAccess(access);
8
- if (refresh)
9
- this.tokensManager.setRefresh(refresh);
10
- };
11
- this.signin = async (input) => {
12
- const url = buildURL(this.host, this.collection + '/signin');
13
- const response = await this.api.post(url, input)
14
- .headers({ 'Content-Type': 'application/json' });
15
- await this._handleApiError(response);
16
- const json = await response.json();
17
- if (json.ok && json.tokens && json.tokens.access && json.tokens.refresh) {
18
- this._setTokens(json.tokens.access, json.tokens.refresh);
19
- }
20
- return json.tokens;
21
- };
22
- this.signup = async (userData) => {
23
- const url = buildURL(this.host, this.collection + '/signup');
24
- const response = await this.api.post(url, userData)
25
- .headers({ 'Content-Type': 'application/json' });
26
- await this._handleApiError(response);
27
- const json = await response.json();
28
- if (json.ok && json.result && json.result.tokens.access && json.result.tokens.refresh) {
29
- this._setTokens(json.result.tokens.access, json.result.tokens.refresh);
30
- }
31
- return json.result.user;
32
- };
33
- this.verify = async () => {
34
- try {
35
- const url = buildURL(this.host, this.collection + '/verify');
36
- const response = await this.api.get(url);
37
- const json = await response.json();
38
- return json.ok ? true : false;
39
- }
40
- catch (error) {
41
- console.warn("Token verification error:", error);
42
- return false;
43
- }
44
- };
45
- this.refresh = async () => {
46
- const url = buildURL(this.host, this.collection + '/refresh');
47
- const response = await this.api.post(url, { refresh: this.tokensManager.refresh })
48
- .headers({ 'Content-Type': 'application/json' });
49
- await this._handleApiError(response);
50
- const json = await response.json();
51
- if (json.ok && json.tokens && json.tokens.access) {
52
- this.tokensManager.setAccess(json.tokens.access);
53
- }
54
- return json.ok ? true : false;
55
- };
56
- this.signout = async () => {
57
- const url = buildURL(this.host, this.collection + '/signout');
58
- const response = await this.api.post(url, {})
59
- .headers({ 'Content-Type': 'application/json' });
60
- await this._handleApiError(response);
61
- const json = await response.json();
62
- if (json.ok)
63
- this.tokensManager.clear();
64
- return json.ok ? true : false;
65
- };
66
8
  this.tokensManager = tokensManager;
67
9
  this.collection = "auth/password";
68
10
  }
11
+ _setTokens = (access, refresh) => {
12
+ this.tokensManager.setAccess(access);
13
+ if (refresh)
14
+ this.tokensManager.setRefresh(refresh);
15
+ };
16
+ login = async (input) => {
17
+ const url = buildURL(this.host, this.collection + '/login');
18
+ const response = await this.api.post(url, input)
19
+ .headers({ 'Content-Type': 'application/json' });
20
+ await this._handleApiError(response);
21
+ const json = await response.json();
22
+ if (json.ok && json.tokens && json.tokens.access && json.tokens.refresh) {
23
+ this._setTokens(json.tokens.access, json.tokens.refresh);
24
+ }
25
+ return json.tokens;
26
+ };
27
+ register = async (userData) => {
28
+ const url = buildURL(this.host, this.collection + '/register');
29
+ const response = await this.api.post(url, userData)
30
+ .headers({ 'Content-Type': 'application/json' });
31
+ await this._handleApiError(response);
32
+ const json = await response.json();
33
+ if (json.ok && json.result && json.result.tokens.access && json.result.tokens.refresh) {
34
+ this._setTokens(json.result.tokens.access, json.result.tokens.refresh);
35
+ }
36
+ return json.result.user;
37
+ };
38
+ verify = async () => {
39
+ try {
40
+ const url = buildURL(this.host, this.collection + '/verify');
41
+ const response = await this.api.get(url);
42
+ const json = await response.json();
43
+ return json.ok ? true : false;
44
+ }
45
+ catch (error) {
46
+ console.warn("Token verification error:", error);
47
+ return false;
48
+ }
49
+ };
50
+ refresh = async () => {
51
+ const url = buildURL(this.host, this.collection + '/refresh');
52
+ const response = await this.api.post(url, { refresh: this.tokensManager.refresh })
53
+ .headers({ 'Content-Type': 'application/json' });
54
+ await this._handleApiError(response);
55
+ const json = await response.json();
56
+ if (json.ok && json.tokens && json.tokens.access) {
57
+ this.tokensManager.setAccess(json.tokens.access);
58
+ }
59
+ return json.ok ? true : false;
60
+ };
61
+ logout = async () => {
62
+ const url = buildURL(this.host, this.collection + '/logout');
63
+ const response = await this.api.post(url, {})
64
+ .headers({ 'Content-Type': 'application/json' });
65
+ await this._handleApiError(response);
66
+ const json = await response.json();
67
+ if (json.ok)
68
+ this.tokensManager.clear();
69
+ return json.ok ? true : false;
70
+ };
69
71
  }
70
72
  export default KodzeroAuthEmail;
@@ -1,12 +1,15 @@
1
1
  import KodzeroAuthBase from "./base.js";
2
2
  import KodzeroAuthEmail from "./email.js";
3
3
  class KodzeroAuth extends KodzeroAuthBase {
4
+ email;
5
+ setTokens;
6
+ clearTokens;
4
7
  constructor(options, api, tokensManager) {
5
8
  super(options, api, tokensManager);
6
9
  this.email = new KodzeroAuthEmail(options, api, tokensManager);
7
- this.signin = this.email.signin;
8
- this.signup = this.email.signup;
9
- this.signout = this.email.signout;
10
+ this.login = this.email.login;
11
+ this.register = this.email.register;
12
+ this.logout = this.email.logout;
10
13
  this.verify = this.email.verify;
11
14
  this.refresh = this.email.refresh;
12
15
  this.setTokens = (access, refresh) => {
@@ -1,4 +1,6 @@
1
1
  class TokensManagerClass {
2
+ access;
3
+ refresh;
2
4
  constructor(access = '', refresh = '') {
3
5
  this.access = access;
4
6
  this.refresh = refresh;
@@ -1,4 +1,7 @@
1
1
  class KodzeroApiError extends Error {
2
+ url;
3
+ statusCode;
4
+ details;
2
5
  constructor(url, statusCode, message, details) {
3
6
  super(message);
4
7
  this.name = "KodzeroApiError";
@@ -1,4 +1,5 @@
1
1
  class KodzeroValidationError extends Error {
2
+ errors;
2
3
  constructor(message, errors = []) {
3
4
  super(message);
4
5
  this.name = "KodzeroValidationError";
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
- export {};
1
+ import Kodzero from "./Kodzero.js";
2
+ export default Kodzero;
package/dist/index.js CHANGED
@@ -1,49 +1,2 @@
1
- import Schema from "validno";
2
1
  import Kodzero from "./Kodzero.js";
3
- console.log('front-sdk started');
4
- const kodzero = new Kodzero({
5
- host: 'http://localhost:6969'
6
- });
7
- const carSchema = new Schema({
8
- _id: { type: String },
9
- mark: { type: String },
10
- model: { type: String },
11
- year: { type: Number }
12
- });
13
- const Car = kodzero.createModel({
14
- collection: 'cars',
15
- schema: carSchema
16
- });
17
- Car.registerMethod('greet', function () {
18
- return `Hello, I am a ${this.modelData.mark} ${this.modelData.model} from ${this.modelData.year}`;
19
- });
20
- const carRecord = await Car.get('68aec23b4732a44b3f559250');
21
- const data = carRecord.data();
22
- console.log(carRecord.greet());
23
- const signRes = await kodzero.auth.email.signin({ email: 'leshatour@gmail.com', password: 'qwerty123' });
24
- const verifyRes = await kodzero.auth.email.verify();
25
- console.log('verify1', verifyRes);
26
- const refreshRes = await kodzero.auth.email.refresh();
27
- console.log('refresh', refreshRes);
28
- const logoutRes = await kodzero.auth.email.signout();
29
- console.log('logout', logoutRes);
30
- const verifyRes2 = await kodzero.auth.email.verify();
31
- console.log('verify2', verifyRes2);
32
- const signupRes = await kodzero.auth.email.signup({
33
- "name": "leshatour2",
34
- "email": `leshatour${Math.random()}@gmail.com`,
35
- "password": "qwerty123"
36
- });
37
- console.log('signup', signupRes);
38
- const URec = kodzero.createModel({
39
- collection: 'scope-user',
40
- schema: new Schema({
41
- text: '134'
42
- })
43
- });
44
- console.log(1);
45
- const urec = new URec({ _id: '', text: 'User Scope Example' });
46
- console.log(2);
47
- await urec.save();
48
- console.log(3);
49
- console.log(urec.data()._id);
2
+ export default Kodzero;
@@ -12,12 +12,12 @@ declare class BaseModel<T extends {
12
12
  collection: string;
13
13
  modelData: T;
14
14
  schema?: typeof Schema;
15
- api: typeof FluidFetch;
15
+ apiClient: typeof FluidFetch;
16
16
  id: string | null;
17
17
  static url: string;
18
18
  static collection: string;
19
19
  static api: typeof FluidFetch;
20
- constructor(options: ModelOptions, api: typeof FluidFetch);
20
+ constructor(options: ModelOptions, apiClient: typeof FluidFetch);
21
21
  _setId: (id: string | null) => void;
22
22
  _setModelData: (data: T) => void;
23
23
  _handleApiError(response: Response): Promise<void>;
@@ -1,36 +1,33 @@
1
- var __rest = (this && this.__rest) || function (s, e) {
2
- var t = {};
3
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
4
- t[p] = s[p];
5
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
6
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
7
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
8
- t[p[i]] = s[p[i]];
9
- }
10
- return t;
11
- };
12
1
  import Schema from "validno";
13
2
  import constants from "./constants.js";
14
- import validateApiResponse from "../utils/validateApiResponse.js";
15
- import BaseModelSchema from "../schemas/baseModel.js";
16
3
  import buildURL from "../utils/buildURL.js";
4
+ import BaseModelSchema from "../schemas/baseModel.js";
5
+ import validateApiResponse from "../utils/validateApiResponse.js";
17
6
  class BaseModel {
18
- constructor(options, api) {
19
- this.modelData = {};
20
- this._setId = (id) => {
21
- this.id = id;
22
- };
23
- this._setModelData = (data) => {
24
- this.modelData = data;
25
- this._setId((data === null || data === void 0 ? void 0 : data._id) || null);
26
- };
7
+ host;
8
+ collection;
9
+ modelData = {};
10
+ schema;
11
+ apiClient;
12
+ id;
13
+ static url;
14
+ static collection;
15
+ static api;
16
+ constructor(options, apiClient) {
27
17
  BaseModelSchema.validateOrThrow(options);
28
18
  this.host = options.host;
29
19
  this.collection = options.collection;
30
- this.schema = options.schema ? new Schema(Object.assign({}, options.schema)) : null;
31
- this.api = api;
20
+ this.schema = options.schema ? new Schema({ ...options.schema }) : null;
21
+ this.apiClient = apiClient;
32
22
  this.id = null;
33
23
  }
24
+ _setId = (id) => {
25
+ this.id = id;
26
+ };
27
+ _setModelData = (data) => {
28
+ this.modelData = data;
29
+ this._setId(data?._id || null);
30
+ };
34
31
  _handleApiError(response) {
35
32
  return validateApiResponse(response);
36
33
  }
@@ -39,7 +36,7 @@ class BaseModel {
39
36
  }
40
37
  _dataWithoutId() {
41
38
  if (typeof this.modelData === 'object' && this.modelData !== null && '_id' in this.modelData) {
42
- const _a = this.modelData, { _id } = _a, dataWithoutId = __rest(_a, ["_id"]);
39
+ const { _id, ...dataWithoutId } = this.modelData;
43
40
  return dataWithoutId;
44
41
  }
45
42
  return this.modelData;
@@ -81,7 +78,7 @@ class BaseModel {
81
78
  throw new Error(constants.RequiresId);
82
79
  }
83
80
  const updateUrl = buildURL(this.host, this.collection, this.id);
84
- const response = await this.api.patch(updateUrl, this._dataWithoutId())
81
+ const response = await this.apiClient.patch(updateUrl, this._dataWithoutId())
85
82
  .headers({ 'Content-Type': 'application/json' });
86
83
  await this._handleApiError(response);
87
84
  const json = await response.json();
@@ -93,7 +90,7 @@ class BaseModel {
93
90
  throw new Error(constants.RequiresId);
94
91
  }
95
92
  const deleteUrl = buildURL(this.host, this.collection, this.id);
96
- const response = await this.api.delete(deleteUrl);
93
+ const response = await this.apiClient.delete(deleteUrl);
97
94
  await this._handleApiError(response);
98
95
  this._setId(null);
99
96
  this.modelData = {};
@@ -101,7 +98,7 @@ class BaseModel {
101
98
  }
102
99
  async create() {
103
100
  const createUrl = buildURL(this.host, this.collection);
104
- const response = await this.api.post(createUrl, this._dataWithoutId())
101
+ const response = await this.apiClient.post(createUrl, this._dataWithoutId())
105
102
  .headers({ 'Content-Type': 'application/json' });
106
103
  await this._handleApiError(response);
107
104
  const json = await response.json();
@@ -0,0 +1,28 @@
1
+ import { FindManyOptions } from "./createModel.js";
2
+ interface PaginationState {
3
+ skip: number;
4
+ limit: number;
5
+ page: number;
6
+ total: number;
7
+ totalPages: number;
8
+ left: number;
9
+ }
10
+ interface PaginationResultInput<T> {
11
+ data: T[];
12
+ state: PaginationState;
13
+ options: FindManyOptions | {};
14
+ findManyFunction: Function;
15
+ }
16
+ declare class PaginatedResult<T = {}> {
17
+ state: PaginationState;
18
+ data: Array<T>;
19
+ options: FindManyOptions | {};
20
+ private findManyFunction;
21
+ constructor(input: PaginationResultInput<T>);
22
+ next(): Promise<PaginatedResult<T>>;
23
+ previous(): Promise<PaginatedResult<T>>;
24
+ page(pageNumber: number): Promise<this>;
25
+ hasNext(): boolean;
26
+ hasPrevious(): boolean;
27
+ }
28
+ export default PaginatedResult;
@@ -0,0 +1,49 @@
1
+ class PaginatedResult {
2
+ state;
3
+ data;
4
+ options;
5
+ findManyFunction;
6
+ constructor(input) {
7
+ const { findManyFunction, state, data, options } = input;
8
+ this.options = options;
9
+ this.findManyFunction = findManyFunction;
10
+ this.state = {
11
+ skip: state.skip || 0,
12
+ limit: state.limit || 0,
13
+ page: state.page || 0,
14
+ total: state.total || 0,
15
+ totalPages: state.totalPages || 0,
16
+ left: state.left || 0
17
+ };
18
+ this.data = data;
19
+ }
20
+ async next() {
21
+ this.state.page++;
22
+ const result = await this.findManyFunction(this.options, this.state.page, this.state.limit);
23
+ this.data = result.data;
24
+ return this;
25
+ }
26
+ async previous() {
27
+ if (this.state.page === 1)
28
+ throw new Error('Page cannot be lower than 1');
29
+ this.state.page--;
30
+ const result = await this.findManyFunction(this.options, this.state.page, this.state.limit);
31
+ this.data = result.data;
32
+ return this;
33
+ }
34
+ async page(pageNumber) {
35
+ if (pageNumber < 1)
36
+ throw new Error('Page cannot be lower than 1');
37
+ this.state.page = pageNumber;
38
+ const result = this.findManyFunction(this.options, this.state.page, this.state.limit);
39
+ this.data = result.data;
40
+ return this;
41
+ }
42
+ hasNext() {
43
+ return this.state.page < this.state.totalPages;
44
+ }
45
+ hasPrevious() {
46
+ return this.state.page > 1;
47
+ }
48
+ }
49
+ export default PaginatedResult;
@@ -1,5 +1,6 @@
1
1
  import FluidFetch from 'fluid-fetch';
2
2
  import BaseModel, { ModelOptions } from './BaseModel.js';
3
+ import PaginatedResult from './PaginatedResult.js';
3
4
  export interface FindManyOptions {
4
5
  page: number;
5
6
  perPage: number;
@@ -9,12 +10,13 @@ export interface FindManyOptions {
9
10
  }
10
11
  declare const createModel: <T extends {
11
12
  _id?: string;
12
- }, M = {}>(options: ModelOptions, api: typeof FluidFetch) => {
13
+ }, M = {}>(options: ModelOptions, apiClient: typeof FluidFetch) => {
13
14
  new (data: T): BaseModel<T> & M;
14
15
  get(id: string): Promise<BaseModel<T> & M>;
15
16
  registerMethod<K extends keyof M>(name: K, fn: M[K]): void;
16
17
  find(id: string): Promise<T>;
17
18
  findMany(options?: FindManyOptions | {}): Promise<T[]>;
19
+ findManyPaginated(options?: FindManyOptions | {}, page?: number, perPage?: number): Promise<PaginatedResult<T>>;
18
20
  create(data: T): Promise<T>;
19
21
  createMany(data: T[]): Promise<T[]>;
20
22
  update(id: string, data: Partial<T>): Promise<T>;