@strapi/database 4.4.3 → 4.5.0-beta.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.
@@ -1,5 +1,8 @@
1
1
  'use strict';
2
2
 
3
+ const { isString } = require('lodash/fp');
4
+ const { isAnyToMany } = require('../metadata/relations');
5
+
3
6
  const withDefaultPagination = (params) => {
4
7
  const { page = 1, pageSize = 10, ...rest } = params;
5
8
 
@@ -10,6 +13,21 @@ const withDefaultPagination = (params) => {
10
13
  };
11
14
  };
12
15
 
16
+ const withOffsetLimit = (params) => {
17
+ const { page, pageSize, ...rest } = withDefaultPagination(params);
18
+
19
+ const offset = Math.max(page - 1, 0) * pageSize;
20
+ const limit = pageSize;
21
+
22
+ const query = {
23
+ ...rest,
24
+ limit,
25
+ offset,
26
+ };
27
+
28
+ return [query, { page, pageSize }];
29
+ };
30
+
13
31
  const createRepository = (uid, db) => {
14
32
  return {
15
33
  findOne(params) {
@@ -28,16 +46,7 @@ const createRepository = (uid, db) => {
28
46
  },
29
47
 
30
48
  async findPage(params) {
31
- const { page, pageSize, ...rest } = withDefaultPagination(params);
32
-
33
- const offset = Math.max(page - 1, 0) * pageSize;
34
- const limit = pageSize;
35
-
36
- const query = {
37
- ...rest,
38
- limit,
39
- offset,
40
- };
49
+ const [query, { page, pageSize }] = withOffsetLimit(params);
41
50
 
42
51
  const [results, total] = await Promise.all([
43
52
  db.entityManager.findMany(uid, query),
@@ -99,8 +108,38 @@ const createRepository = (uid, db) => {
99
108
  return db.entityManager.populate(uid, entity, populate);
100
109
  },
101
110
 
102
- load(entity, field, params) {
103
- return db.entityManager.load(uid, entity, field, params);
111
+ load(entity, fields, params) {
112
+ return db.entityManager.load(uid, entity, fields, params);
113
+ },
114
+
115
+ async loadPages(entity, field, params) {
116
+ if (!isString(field)) {
117
+ throw new Error(`Invalid load. Expected ${field} to be a string`);
118
+ }
119
+
120
+ const { attributes } = db.metadata.get(uid);
121
+ const attribute = attributes[field];
122
+
123
+ if (!attribute || attribute.type !== 'relation' || !isAnyToMany(attribute)) {
124
+ throw new Error(`Invalid load. Expected ${field} to be an anyToMany relational attribute`);
125
+ }
126
+
127
+ const [query, { page, pageSize }] = withOffsetLimit(params);
128
+
129
+ const [results, { count: total }] = await Promise.all([
130
+ db.entityManager.load(uid, entity, field, query),
131
+ db.entityManager.load(uid, entity, field, { ...query, count: true }),
132
+ ]);
133
+
134
+ return {
135
+ results,
136
+ pagination: {
137
+ page,
138
+ pageSize,
139
+ pageCount: Math.ceil(total / pageSize),
140
+ total,
141
+ },
142
+ };
104
143
  },
105
144
  };
106
145
  };