@strapi/plugin-documentation 4.1.10-beta.0 → 4.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,41 @@
1
+ 'use strict';
2
+
3
+ const strapi = {
4
+ plugins: {
5
+ 'users-permissions': {
6
+ contentTypes: {
7
+ role: {
8
+ attributes: {
9
+ name: {
10
+ type: 'string',
11
+ },
12
+ },
13
+ },
14
+ },
15
+ routes: {
16
+ 'content-api': {
17
+ routes: [],
18
+ },
19
+ },
20
+ },
21
+ },
22
+ api: {
23
+ restaurant: {
24
+ contentTypes: {
25
+ restaurant: {
26
+ attributes: {
27
+ name: {
28
+ type: 'string',
29
+ },
30
+ },
31
+ },
32
+ },
33
+ routes: {
34
+ restaurant: { routes: [] },
35
+ },
36
+ },
37
+ },
38
+ contentType: () => ({ info: {}, attributes: { test: { type: 'string' } } }),
39
+ };
40
+
41
+ module.exports = strapi;
@@ -0,0 +1,266 @@
1
+ 'use strict';
2
+
3
+ const _ = require('lodash');
4
+ const buildComponentSchema = require('../server/services/helpers/build-component-schema');
5
+ const strapi = require('../__mocks__/strapi');
6
+
7
+ describe('Build Component Schema', () => {
8
+ beforeEach(() => {
9
+ // Reset the mocked strapi instance
10
+ global.strapi = _.cloneDeep(strapi);
11
+ });
12
+
13
+ it('builds the Response schema', () => {
14
+ const apiMocks = [
15
+ {
16
+ name: 'users-permissions',
17
+ getter: 'plugin',
18
+ ctNames: ['role'],
19
+ },
20
+ { name: 'restaurant', getter: 'api', ctNames: ['restaurant'] },
21
+ ];
22
+
23
+ let schemas = {};
24
+ for (const mock of apiMocks) {
25
+ schemas = {
26
+ ...schemas,
27
+ ...buildComponentSchema(mock),
28
+ };
29
+ }
30
+
31
+ const schemaNames = Object.keys(schemas);
32
+ const [pluginResponseName, apiResponseName] = Object.keys(schemas);
33
+ const [pluginResponseValue, apiResponseValue] = Object.values(schemas);
34
+
35
+ const expectedShape = {
36
+ properties: {
37
+ data: {
38
+ type: 'object',
39
+ properties: {
40
+ id: { type: 'string' },
41
+ attributes: { type: 'object', properties: { test: { type: 'string' } } },
42
+ },
43
+ },
44
+ meta: { type: 'object' },
45
+ },
46
+ };
47
+
48
+ expect(schemaNames.length).toBe(2);
49
+ expect(pluginResponseName).toBe('UsersPermissionsRoleResponse');
50
+ expect(apiResponseName).toBe('RestaurantResponse');
51
+ expect(pluginResponseValue).toStrictEqual(expectedShape);
52
+ expect(apiResponseValue).toStrictEqual(expectedShape);
53
+ });
54
+
55
+ it('builds the ResponseList schema', () => {
56
+ global.strapi.plugins['users-permissions'].routes['content-api'].routes = [
57
+ { method: 'GET', path: '/test', handler: 'test.find' },
58
+ ];
59
+ global.strapi.api.restaurant.routes.restaurant.routes = [
60
+ { method: 'GET', path: '/test', handler: 'test.find' },
61
+ ];
62
+
63
+ const apiMocks = [
64
+ {
65
+ name: 'users-permissions',
66
+ getter: 'plugin',
67
+ ctNames: ['role'],
68
+ },
69
+ { name: 'restaurant', getter: 'api', ctNames: ['restaurant'] },
70
+ ];
71
+
72
+ let schemas = {};
73
+ for (const mock of apiMocks) {
74
+ schemas = {
75
+ ...schemas,
76
+ ...buildComponentSchema(mock),
77
+ };
78
+ }
79
+
80
+ const schemaNames = Object.keys(schemas);
81
+ const pluginListResponseValue = schemas['UsersPermissionsRoleListResponse'];
82
+ const apiListResponseValue = schemas['RestaurantListResponse'];
83
+
84
+ const expectedShape = {
85
+ properties: {
86
+ data: {
87
+ type: 'array',
88
+ items: {
89
+ type: 'object',
90
+ properties: {
91
+ id: { type: 'string' },
92
+ attributes: { type: 'object', properties: { test: { type: 'string' } } },
93
+ },
94
+ },
95
+ },
96
+ meta: {
97
+ type: 'object',
98
+ properties: {
99
+ pagination: {
100
+ properties: {
101
+ page: { type: 'integer' },
102
+ pageSize: { type: 'integer', minimum: 25 },
103
+ pageCount: { type: 'integer', maximum: 1 },
104
+ total: { type: 'integer' },
105
+ },
106
+ },
107
+ },
108
+ },
109
+ },
110
+ };
111
+
112
+ expect(schemaNames.length).toBe(4);
113
+ expect(schemaNames.includes('UsersPermissionsRoleListResponse')).toBe(true);
114
+ expect(schemaNames.includes('RestaurantListResponse')).toBe(true);
115
+ expect(pluginListResponseValue).toStrictEqual(expectedShape);
116
+ expect(apiListResponseValue).toStrictEqual(expectedShape);
117
+ });
118
+
119
+ it('builds the Request schema', () => {
120
+ global.strapi.plugins['users-permissions'].routes['content-api'].routes = [
121
+ { method: 'POST', path: '/test', handler: 'test.create' },
122
+ ];
123
+ global.strapi.api.restaurant.routes.restaurant.routes = [
124
+ { method: 'POST', path: '/test', handler: 'test.create' },
125
+ ];
126
+
127
+ const apiMocks = [
128
+ {
129
+ name: 'users-permissions',
130
+ getter: 'plugin',
131
+ ctNames: ['role'],
132
+ },
133
+ { name: 'restaurant', getter: 'api', ctNames: ['restaurant'] },
134
+ ];
135
+
136
+ let schemas = {};
137
+ for (const mock of apiMocks) {
138
+ schemas = {
139
+ ...schemas,
140
+ ...buildComponentSchema(mock),
141
+ };
142
+ }
143
+
144
+ const schemaNames = Object.keys(schemas);
145
+ const pluginListResponseValue = schemas['UsersPermissionsRoleRequest'];
146
+ const apiListResponseValue = schemas['RestaurantRequest'];
147
+
148
+ const expectedShape = {
149
+ type: 'object',
150
+ properties: {
151
+ data: {
152
+ type: 'object',
153
+ properties: { test: { type: 'string' } },
154
+ },
155
+ },
156
+ };
157
+
158
+ expect(schemaNames.length).toBe(4);
159
+ expect(schemaNames.includes('UsersPermissionsRoleRequest')).toBe(true);
160
+ expect(schemaNames.includes('RestaurantRequest')).toBe(true);
161
+ expect(pluginListResponseValue).toStrictEqual(expectedShape);
162
+ expect(apiListResponseValue).toStrictEqual(expectedShape);
163
+ });
164
+
165
+ it('builds the LocalizationResponse schema', () => {
166
+ global.strapi.plugins['users-permissions'].routes['content-api'].routes = [
167
+ { method: 'GET', path: '/localizations', handler: 'test' },
168
+ ];
169
+ global.strapi.api.restaurant.routes.restaurant.routes = [
170
+ { method: 'GET', path: '/localizations', handler: 'test' },
171
+ ];
172
+
173
+ const apiMocks = [
174
+ {
175
+ name: 'users-permissions',
176
+ getter: 'plugin',
177
+ ctNames: ['role'],
178
+ },
179
+ { name: 'restaurant', getter: 'api', ctNames: ['restaurant'] },
180
+ ];
181
+
182
+ let schemas = {};
183
+ for (const mock of apiMocks) {
184
+ schemas = {
185
+ ...schemas,
186
+ ...buildComponentSchema(mock),
187
+ };
188
+ }
189
+
190
+ const schemaNames = Object.keys(schemas);
191
+ const pluginListResponseValue = schemas['UsersPermissionsRoleLocalizationResponse'];
192
+ const apiListResponseValue = schemas['RestaurantLocalizationResponse'];
193
+
194
+ const expectedShape = {
195
+ type: 'object',
196
+ properties: {
197
+ id: { type: 'string' },
198
+ test: { type: 'string' },
199
+ },
200
+ };
201
+
202
+ expect(schemaNames.length).toBe(4);
203
+ expect(schemaNames.includes('UsersPermissionsRoleLocalizationResponse')).toBe(true);
204
+ expect(schemaNames.includes('RestaurantLocalizationResponse')).toBe(true);
205
+ expect(pluginListResponseValue).toStrictEqual(expectedShape);
206
+ expect(apiListResponseValue).toStrictEqual(expectedShape);
207
+ });
208
+
209
+ it('builds the LocalizationRequest schema', () => {
210
+ global.strapi.plugins['users-permissions'].routes['content-api'].routes = [
211
+ { method: 'POST', path: '/localizations', handler: 'test' },
212
+ ];
213
+ global.strapi.api.restaurant.routes.restaurant.routes = [
214
+ { method: 'POST', path: '/localizations', handler: 'test' },
215
+ ];
216
+
217
+ const apiMocks = [
218
+ {
219
+ name: 'users-permissions',
220
+ getter: 'plugin',
221
+ ctNames: ['role'],
222
+ },
223
+ { name: 'restaurant', getter: 'api', ctNames: ['restaurant'] },
224
+ ];
225
+
226
+ let schemas = {};
227
+ for (const mock of apiMocks) {
228
+ schemas = {
229
+ ...schemas,
230
+ ...buildComponentSchema(mock),
231
+ };
232
+ }
233
+
234
+ const schemaNames = Object.keys(schemas);
235
+ const pluginListResponseValue = schemas['UsersPermissionsRoleLocalizationRequest'];
236
+ const apiListResponseValue = schemas['RestaurantLocalizationRequest'];
237
+
238
+ const expectedShape = {
239
+ type: 'object',
240
+ properties: { test: { type: 'string' } },
241
+ };
242
+
243
+ expect(schemaNames.length).toBe(8);
244
+ expect(schemaNames.includes('UsersPermissionsRoleLocalizationRequest')).toBe(true);
245
+ expect(schemaNames.includes('RestaurantLocalizationRequest')).toBe(true);
246
+ expect(pluginListResponseValue).toStrictEqual(expectedShape);
247
+ expect(apiListResponseValue).toStrictEqual(expectedShape);
248
+ });
249
+
250
+ it('creates the correct name given multiple content types', () => {
251
+ const apiMock = {
252
+ name: 'users-permissions',
253
+ getter: 'plugin',
254
+ ctNames: ['permission', 'role', 'user'],
255
+ };
256
+
257
+ const schemas = buildComponentSchema(apiMock);
258
+ const schemaNames = Object.keys(schemas);
259
+ const [permission, role, user] = schemaNames;
260
+
261
+ expect(schemaNames.length).toBe(3);
262
+ expect(permission).toBe('UsersPermissionsPermissionResponse');
263
+ expect(role).toBe('UsersPermissionsRoleResponse');
264
+ expect(user).toBe('UsersPermissionsUserResponse');
265
+ });
266
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@strapi/plugin-documentation",
3
- "version": "4.1.10-beta.0",
3
+ "version": "4.1.10",
4
4
  "description": "Create an OpenAPI Document and visualize your API with SWAGGER UI.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -24,8 +24,8 @@
24
24
  "test": "echo \"no tests yet\""
25
25
  },
26
26
  "dependencies": {
27
- "@strapi/helper-plugin": "4.1.10-beta.0",
28
- "@strapi/utils": "4.1.10-beta.0",
27
+ "@strapi/helper-plugin": "4.1.10",
28
+ "@strapi/utils": "4.1.10",
29
29
  "bcryptjs": "2.4.3",
30
30
  "cheerio": "^1.0.0-rc.5",
31
31
  "fs-extra": "10.0.0",
@@ -57,5 +57,5 @@
57
57
  "description": "Create an OpenAPI Document and visualize your API with SWAGGER UI.",
58
58
  "kind": "plugin"
59
59
  },
60
- "gitHead": "a9082d9a3b26bf0abeb8e45d4507d5329e9ae733"
60
+ "gitHead": "06abcda86ab96fc560b3ff5e3d72c4d5c1c5d42c"
61
61
  }
@@ -21,7 +21,7 @@ module.exports = {
21
21
  path: '/documentation',
22
22
  showGeneratedFiles: true,
23
23
  generateDefaultResponse: true,
24
- plugins: ['email', 'upload'],
24
+ plugins: ['email', 'upload', 'users-permissions'],
25
25
  },
26
26
  servers: [],
27
27
  externalDocs: {
@@ -41,5 +41,34 @@ module.exports = {
41
41
  bearerFormat: 'JWT',
42
42
  },
43
43
  },
44
+ schemas: {
45
+ Error: {
46
+ type: 'object',
47
+ required: ['error'],
48
+ properties: {
49
+ data: {
50
+ nullable: true,
51
+ oneOf: [{ type: 'object' }, { type: 'array' }],
52
+ },
53
+ error: {
54
+ type: 'object',
55
+ properties: {
56
+ status: {
57
+ type: 'integer',
58
+ },
59
+ name: {
60
+ type: 'string',
61
+ },
62
+ message: {
63
+ type: 'string',
64
+ },
65
+ details: {
66
+ type: 'object',
67
+ },
68
+ },
69
+ },
70
+ },
71
+ },
72
+ },
44
73
  },
45
74
  };
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- const defaultDocumentationConfig = require('./default-config');
3
+ const defaultPluginConfig = require('./default-plugin-config');
4
4
 
5
5
  module.exports = {
6
- default: defaultDocumentationConfig,
6
+ default: defaultPluginConfig,
7
7
  };
@@ -5,8 +5,8 @@ const fs = require('fs-extra');
5
5
  const _ = require('lodash');
6
6
  const { getAbsoluteServerUrl } = require('@strapi/utils');
7
7
 
8
- const { builApiEndpointPath } = require('../utils/builders');
9
- const defaultConfig = require('../config/default-config');
8
+ const defaultPluginConfig = require('../config/default-plugin-config');
9
+ const { builApiEndpointPath, buildComponentSchema } = require('./helpers');
10
10
 
11
11
  module.exports = ({ strapi }) => {
12
12
  const config = strapi.config.get('plugin.documentation');
@@ -107,7 +107,7 @@ module.exports = ({ strapi }) => {
107
107
  return [...apisToDocument, ...pluginsToDocument];
108
108
  },
109
109
 
110
- async getCustomSettings() {
110
+ async getCustomConfig() {
111
111
  const customConfigPath = this.getCustomDocumentationPath();
112
112
  const pathExists = await fs.pathExists(customConfigPath);
113
113
  if (pathExists) {
@@ -122,23 +122,31 @@ module.exports = ({ strapi }) => {
122
122
  */
123
123
  async generateFullDoc(version = this.getDocumentationVersion()) {
124
124
  let paths = {};
125
-
125
+ let schemas = {};
126
126
  const apis = this.getPluginAndApiInfo();
127
127
  for (const api of apis) {
128
128
  const apiName = api.name;
129
129
  const apiDirPath = path.join(this.getApiDocumentationPath(api), version);
130
130
 
131
131
  const apiDocPath = path.join(apiDirPath, `${apiName}.json`);
132
- const apiPathsObject = builApiEndpointPath(api);
133
132
 
134
- if (!apiPathsObject) {
133
+ const apiPath = builApiEndpointPath(api);
134
+
135
+ if (!apiPath) {
135
136
  continue;
136
137
  }
137
138
 
138
139
  await fs.ensureFile(apiDocPath);
139
- await fs.writeJson(apiDocPath, apiPathsObject, { spaces: 2 });
140
+ await fs.writeJson(apiDocPath, apiPath, { spaces: 2 });
140
141
 
141
- paths = { ...paths, ...apiPathsObject.paths };
142
+ const componentSchema = buildComponentSchema(api);
143
+
144
+ schemas = {
145
+ ...schemas,
146
+ ...componentSchema,
147
+ };
148
+
149
+ paths = { ...paths, ...apiPath };
142
150
  }
143
151
 
144
152
  const fullDocJsonPath = path.join(
@@ -147,27 +155,26 @@ module.exports = ({ strapi }) => {
147
155
  'full_documentation.json'
148
156
  );
149
157
 
150
- const defaultSettings = _.cloneDeep(defaultConfig);
158
+ const defaultConfig = _.cloneDeep(defaultPluginConfig);
151
159
 
152
160
  const serverUrl = getAbsoluteServerUrl(strapi.config);
153
161
  const apiPath = strapi.config.get('api.rest.prefix');
154
162
 
155
- _.set(defaultSettings, 'servers', [
163
+ _.set(defaultConfig, 'servers', [
156
164
  {
157
165
  url: `${serverUrl}${apiPath}`,
158
166
  description: 'Development server',
159
167
  },
160
168
  ]);
169
+ _.set(defaultConfig, ['info', 'x-generation-date'], new Date().toISOString());
170
+ _.set(defaultConfig, ['info', 'version'], version);
171
+ _.merge(defaultConfig.components, { schemas });
161
172
 
162
- _.set(defaultSettings, ['info', 'x-generation-date'], new Date().toISOString());
163
- _.set(defaultSettings, ['info', 'version'], version);
164
-
165
- const customSettings = await this.getCustomSettings();
166
-
167
- const settings = _.merge(defaultSettings, customSettings);
173
+ const customConfig = await this.getCustomConfig();
174
+ const config = _.merge(defaultConfig, customConfig);
168
175
 
169
176
  await fs.ensureFile(fullDocJsonPath);
170
- await fs.writeJson(fullDocJsonPath, { ...settings, paths }, { spaces: 2 });
177
+ await fs.writeJson(fullDocJsonPath, { ...config, paths }, { spaces: 2 });
171
178
  },
172
179
  };
173
180
  };
@@ -0,0 +1,185 @@
1
+ 'use strict';
2
+
3
+ const _ = require('lodash');
4
+ const pathToRegexp = require('path-to-regexp');
5
+
6
+ const pascalCase = require('./utils/pascal-case');
7
+ const queryParams = require('./utils/query-params');
8
+ const loopContentTypeNames = require('./utils/loop-content-type-names');
9
+ const getApiResponses = require('./utils/get-api-responses');
10
+ const { hasFindMethod, isLocalizedPath } = require('./utils/routes');
11
+
12
+ /**
13
+ * @description Parses a route with ':variable'
14
+ *
15
+ * @param {string} routePath - The route's path property
16
+ * @returns {string}
17
+ */
18
+ const parsePathWithVariables = (routePath) => {
19
+ return pathToRegexp
20
+ .parse(routePath)
21
+ .map((token) => {
22
+ if (_.isObject(token)) {
23
+ return token.prefix + '{' + token.name + '}';
24
+ }
25
+
26
+ return token;
27
+ })
28
+ .join('');
29
+ };
30
+
31
+ /**
32
+ * @description Builds the required object for a path parameter
33
+ *
34
+ * @param {string} routePath - The route's path property
35
+ *
36
+ * @returns {object } Swagger path params object
37
+ */
38
+ const getPathParams = (routePath) => {
39
+ return pathToRegexp
40
+ .parse(routePath)
41
+ .filter((token) => _.isObject(token))
42
+ .map((param) => {
43
+ return {
44
+ name: param.name,
45
+ in: 'path',
46
+ description: '',
47
+ deprecated: false,
48
+ required: true,
49
+ schema: { type: 'string' },
50
+ };
51
+ });
52
+ };
53
+
54
+ /**
55
+ *
56
+ * @param {string} prefix - The prefix found on the routes object
57
+ * @param {string} route - The current route
58
+ * @property {string} route.path - The current route's path
59
+ * @property {object} route.config - The current route's config object
60
+ *
61
+ * @returns {string}
62
+ */
63
+ const getPathWithPrefix = (prefix, route) => {
64
+ // When the prefix is set on the routes and
65
+ // the current route is not trying to remove it
66
+ if (prefix && !_.has(route.config, 'prefix')) {
67
+ // Add the prefix to the path
68
+ return prefix.concat(route.path);
69
+ }
70
+
71
+ // Otherwise just return path
72
+ return route.path;
73
+ };
74
+ /**
75
+ * @description Gets all paths based on routes
76
+ *
77
+ * @param {object} apiInfo
78
+ * @property {object} apiInfo.routeInfo - The api routes object
79
+ * @property {string} apiInfo.uniqueName - Content type name | Api name + Content type name
80
+ * @property {object} apiInfo.contentTypeInfo - The info object found on content type schemas
81
+ *
82
+ * @returns {object}
83
+ */
84
+ const getPaths = ({ routeInfo, uniqueName, contentTypeInfo }) => {
85
+ // Get the routes for the current content type
86
+ const contentTypeRoutes = routeInfo.routes.filter((route) => {
87
+ return (
88
+ route.path.includes(contentTypeInfo.pluralName) ||
89
+ route.path.includes(contentTypeInfo.singularName)
90
+ );
91
+ });
92
+
93
+ const paths = contentTypeRoutes.reduce((acc, route) => {
94
+ // TODO: Find a more reliable way to determine list of entities vs a single entity
95
+ const isListOfEntities = hasFindMethod(route.handler);
96
+ const isLocalizationPath = isLocalizedPath(route.path);
97
+ const methodVerb = route.method.toLowerCase();
98
+ const hasPathParams = route.path.includes('/:');
99
+ const pathWithPrefix = getPathWithPrefix(routeInfo.prefix, route);
100
+ const routePath = hasPathParams ? parsePathWithVariables(pathWithPrefix) : pathWithPrefix;
101
+ const { responses } = getApiResponses({
102
+ uniqueName,
103
+ route,
104
+ isListOfEntities,
105
+ isLocalizationPath,
106
+ });
107
+
108
+ const swaggerConfig = {
109
+ responses,
110
+ tags: [_.upperFirst(uniqueName)],
111
+ parameters: [],
112
+ operationId: `${methodVerb}${routePath}`,
113
+ };
114
+
115
+ if (isListOfEntities) {
116
+ swaggerConfig.parameters.push(...queryParams);
117
+ }
118
+
119
+ if (hasPathParams) {
120
+ const pathParams = getPathParams(route.path);
121
+ swaggerConfig.parameters.push(...pathParams);
122
+ }
123
+
124
+ if (['post', 'put'].includes(methodVerb)) {
125
+ const refName = isLocalizationPath ? 'LocalizationRequest' : 'Request';
126
+ const requestBody = {
127
+ required: true,
128
+ content: {
129
+ 'application/json': {
130
+ schema: {
131
+ $ref: `#/components/schemas/${pascalCase(uniqueName)}${refName}`,
132
+ },
133
+ },
134
+ },
135
+ };
136
+
137
+ swaggerConfig.requestBody = requestBody;
138
+ }
139
+
140
+ _.set(acc, `${routePath}.${methodVerb}`, swaggerConfig);
141
+
142
+ return acc;
143
+ }, {});
144
+
145
+ return paths;
146
+ };
147
+
148
+ /**
149
+ * @decription Gets all open api paths object for a given content type
150
+ *
151
+ * @param {object} apiInfo
152
+ *
153
+ * @returns {object} Open API paths
154
+ */
155
+ const getAllPathsForContentType = (apiInfo) => {
156
+ let paths = {};
157
+
158
+ const pathsObject = getPaths(apiInfo);
159
+
160
+ paths = {
161
+ ...paths,
162
+ ...pathsObject,
163
+ };
164
+
165
+ return paths;
166
+ };
167
+
168
+ /**
169
+ * @description - Builds the Swagger paths object for each api
170
+ *
171
+ * @param {object} api - Information about the current api
172
+ * @property {string} api.name - The name of the api
173
+ * @property {string} api.getter - The getter for the api (api | plugin)
174
+ * @property {array} api.ctNames - The name of all contentTypes found on the api
175
+ *
176
+ * @returns {object}
177
+ */
178
+ const buildApiEndpointPath = (api) => {
179
+ // A reusable loop for building paths and component schemas
180
+ // Uses the api param to build a new set of params for each content type
181
+ // Passes these new params to the function provided
182
+ return loopContentTypeNames(api, getAllPathsForContentType);
183
+ };
184
+
185
+ module.exports = buildApiEndpointPath;