@knovator/pagecreator-node 0.2.0 → 0.4.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.
Files changed (120) hide show
  1. package/package.json +6 -3
  2. package/src/constants/index.d.ts +16 -0
  3. package/src/constants/index.js +30 -0
  4. package/src/constants/index.js.map +1 -0
  5. package/src/controllers/ItemController.d.ts +4 -0
  6. package/src/controllers/ItemController.js +108 -0
  7. package/src/controllers/ItemController.js.map +1 -0
  8. package/src/controllers/PageController.d.ts +4 -0
  9. package/src/controllers/PageController.js +61 -0
  10. package/src/controllers/PageController.js.map +1 -0
  11. package/src/controllers/UserController.d.ts +2 -0
  12. package/src/controllers/UserController.js +238 -0
  13. package/src/controllers/UserController.js.map +1 -0
  14. package/src/controllers/WidgetController.d.ts +8 -0
  15. package/src/controllers/WidgetController.js +131 -0
  16. package/src/controllers/WidgetController.js.map +1 -0
  17. package/src/index.d.ts +8 -0
  18. package/src/index.js +29 -0
  19. package/src/index.js.map +1 -0
  20. package/src/models/Item.d.ts +3 -0
  21. package/src/models/Item.js +30 -0
  22. package/src/models/Item.js.map +1 -0
  23. package/src/models/Page.d.ts +3 -0
  24. package/src/models/Page.js +16 -0
  25. package/src/models/Page.js.map +1 -0
  26. package/src/models/SrcSet.d.ts +4 -0
  27. package/src/models/SrcSet.js +15 -0
  28. package/src/models/SrcSet.js.map +1 -0
  29. package/src/models/Widget.d.ts +3 -0
  30. package/src/models/Widget.js +42 -0
  31. package/src/models/Widget.js.map +1 -0
  32. package/src/models/{index.ts → index.d.ts} +0 -1
  33. package/src/models/index.js +13 -0
  34. package/src/models/index.js.map +1 -0
  35. package/src/plugins/softDelete.d.ts +7 -0
  36. package/src/plugins/softDelete.js +64 -0
  37. package/src/plugins/softDelete.js.map +1 -0
  38. package/src/routes/ItemRoute.d.ts +3 -0
  39. package/src/routes/ItemRoute.js +31 -0
  40. package/src/routes/ItemRoute.js.map +1 -0
  41. package/src/routes/PageRoute.d.ts +3 -0
  42. package/src/routes/PageRoute.js +30 -0
  43. package/src/routes/PageRoute.js.map +1 -0
  44. package/src/routes/UserRoute.d.ts +3 -0
  45. package/src/routes/UserRoute.js +23 -0
  46. package/src/routes/UserRoute.js.map +1 -0
  47. package/src/routes/WidgetRoute.d.ts +3 -0
  48. package/src/routes/WidgetRoute.js +47 -0
  49. package/src/routes/WidgetRoute.js.map +1 -0
  50. package/src/services/dbService.d.ts +10 -0
  51. package/src/services/dbService.js +74 -0
  52. package/src/services/dbService.js.map +1 -0
  53. package/src/types/{IRequest.ts → IRequest.d.ts} +3 -4
  54. package/src/types/IRequest.js +3 -0
  55. package/src/types/IRequest.js.map +1 -0
  56. package/src/types/{IResponse.ts → IResponse.d.ts} +3 -4
  57. package/src/types/IResponse.js +3 -0
  58. package/src/types/IResponse.js.map +1 -0
  59. package/src/types/{Router.ts → Router.d.ts} +1 -2
  60. package/src/types/Router.js +3 -0
  61. package/src/types/Router.js.map +1 -0
  62. package/src/types/common.d.ts +93 -0
  63. package/src/types/common.js +3 -0
  64. package/src/types/common.js.map +1 -0
  65. package/src/types/enums.d.ts +11 -0
  66. package/src/types/enums.js +18 -0
  67. package/src/types/enums.js.map +1 -0
  68. package/src/types/{index.ts → index.d.ts} +0 -0
  69. package/src/types/index.js +9 -0
  70. package/src/types/index.js.map +1 -0
  71. package/src/utils/defaults.d.ts +7 -0
  72. package/src/utils/defaults.js +28 -0
  73. package/src/utils/defaults.js.map +1 -0
  74. package/src/utils/helper.d.ts +33 -0
  75. package/src/utils/helper.js +111 -0
  76. package/src/utils/helper.js.map +1 -0
  77. package/src/utils/responseHandlers.d.ts +6 -0
  78. package/src/utils/responseHandlers.js +57 -0
  79. package/src/utils/responseHandlers.js.map +1 -0
  80. package/src/utils/validate.d.ts +4 -0
  81. package/src/utils/validate.js +24 -0
  82. package/src/utils/validate.js.map +1 -0
  83. package/src/utils/validations/item.d.ts +7 -0
  84. package/src/utils/validations/item.js +52 -0
  85. package/src/utils/validations/item.js.map +1 -0
  86. package/src/utils/validations/page.d.ts +7 -0
  87. package/src/utils/validations/page.js +58 -0
  88. package/src/utils/validations/page.js.map +1 -0
  89. package/src/utils/validations/user.d.ts +3 -0
  90. package/src/utils/validations/user.js +12 -0
  91. package/src/utils/validations/user.js.map +1 -0
  92. package/src/utils/validations/widget.d.ts +9 -0
  93. package/src/utils/validations/widget.js +116 -0
  94. package/src/utils/validations/widget.js.map +1 -0
  95. package/src/constants/index.ts +0 -26
  96. package/src/controllers/ItemController.ts +0 -139
  97. package/src/controllers/PageController.ts +0 -65
  98. package/src/controllers/UserController.ts +0 -265
  99. package/src/controllers/WidgetController.ts +0 -165
  100. package/src/index.ts +0 -29
  101. package/src/models/Item.ts +0 -29
  102. package/src/models/Page.ts +0 -17
  103. package/src/models/SrcSet.ts +0 -16
  104. package/src/models/Widget.ts +0 -44
  105. package/src/plugins/softDelete.ts +0 -84
  106. package/src/routes/ItemRoute.ts +0 -32
  107. package/src/routes/PageRoute.ts +0 -31
  108. package/src/routes/UserRoute.ts +0 -32
  109. package/src/routes/WidgetRoute.ts +0 -56
  110. package/src/services/dbService.ts +0 -82
  111. package/src/types/common.ts +0 -130
  112. package/src/types/enums.ts +0 -13
  113. package/src/utils/defaults.ts +0 -30
  114. package/src/utils/helper.ts +0 -133
  115. package/src/utils/responseHandlers.ts +0 -54
  116. package/src/utils/validate.ts +0 -22
  117. package/src/utils/validations/item.ts +0 -51
  118. package/src/utils/validations/page.ts +0 -59
  119. package/src/utils/validations/user.ts +0 -9
  120. package/src/utils/validations/widget.ts +0 -118
@@ -1,31 +0,0 @@
1
- import express from 'express';
2
- // eslint-disable-next-line @typescript-eslint/no-var-requires
3
- require('express-list-endpoints-descriptor')(express);
4
- import { IRouter } from '../types';
5
-
6
- import validate from '../utils/validate';
7
- import * as pageValidation from '../utils/validations/page';
8
- import * as pageController from '../controllers/PageController';
9
-
10
- const descriptorPrefix = process.env['PAGECREATOR_DESCRIPTOR_PREFIX'] || '';
11
- const routes = express.Router() as IRouter;
12
- routes.use(express.json());
13
-
14
- // Get all pages
15
- routes
16
- .post(`/list`, validate(pageValidation.list), pageController.getPages)
17
- .descriptor(`${descriptorPrefix}page.getAll`);
18
- // Create a page
19
- routes
20
- .post(`/`, validate(pageValidation.create), pageController.createPage)
21
- .descriptor(`${descriptorPrefix}page.create`);
22
- // Update a page
23
- routes
24
- .put(`/:id`, validate(pageValidation.update), pageController.updatePage)
25
- .descriptor(`${descriptorPrefix}page.update`);
26
- // Delete a page
27
- routes
28
- .delete(`/:id`, pageController.deletePage)
29
- .descriptor(`${descriptorPrefix}page.delete`);
30
-
31
- export default routes;
@@ -1,32 +0,0 @@
1
- import express from 'express';
2
- // eslint-disable-next-line @typescript-eslint/no-var-requires
3
- require('express-list-endpoints-descriptor')(express);
4
- import { IRouter } from '../types';
5
-
6
- import validate from '../utils/validate';
7
- import * as userValidation from '../utils/validations/user';
8
- import * as userController from '../controllers/UserController';
9
-
10
- const descriptorPrefix = process.env['PAGECREATOR_DESCRIPTOR_PREFIX'] || '';
11
- const routes = express.Router() as IRouter;
12
- routes.use(express.json());
13
-
14
- // Item Routes
15
- // Get Widget Data
16
- routes
17
- .post(
18
- `/widget-data`,
19
- validate(userValidation.getWidgetData),
20
- userController.getWidgetData
21
- )
22
- .descriptor(`${descriptorPrefix}user.getWidgetData`);
23
- // Get Page Data
24
- routes
25
- .post(
26
- '/page-data',
27
- validate(userValidation.getPageData),
28
- userController.getPageData
29
- )
30
- .descriptor(`${descriptorPrefix}user.getPageData`);
31
-
32
- export default routes;
@@ -1,56 +0,0 @@
1
- import express from 'express';
2
- // eslint-disable-next-line @typescript-eslint/no-var-requires
3
- require('express-list-endpoints-descriptor')(express);
4
- import { IRouter } from '../types';
5
-
6
- import validate from '../utils/validate';
7
- import * as widgetValidation from '../utils/validations/widget';
8
- import * as widgetController from '../controllers/WidgetController';
9
-
10
- const descriptorPrefix = process.env['PAGECREATOR_DESCRIPTOR_PREFIX'] || '';
11
- const routes = express.Router() as IRouter;
12
- routes.use(express.json());
13
-
14
- // Widget Routes
15
- // Get widget types
16
- routes
17
- .get('/widget-types', widgetController.getItemsTypes)
18
- .descriptor(`${descriptorPrefix}widget.getItemsTypes`);
19
- // Get widget selection types
20
- routes
21
- .get('/selection-types', widgetController.getWidgetTypes)
22
- .descriptor(`${descriptorPrefix}widget.getWidgetTypes`);
23
- // Get all widgets
24
- routes
25
- .post(`/list`, validate(widgetValidation.list), widgetController.getWidgets)
26
- .descriptor(`${descriptorPrefix}widget.getAll`);
27
- // Create a widget
28
- routes
29
- .post(`/`, validate(widgetValidation.create), widgetController.createWidget)
30
- .descriptor(`${descriptorPrefix}widget.create`);
31
- // Update a widget
32
- routes
33
- .put(`/:id`, validate(widgetValidation.update), widgetController.updateWidget)
34
- .descriptor(`${descriptorPrefix}widget.update`);
35
- // Partial Update a widget
36
- routes
37
- .patch(
38
- `/:id`,
39
- validate(widgetValidation.partialUpdate),
40
- widgetController.partialUpdateWidget
41
- )
42
- .descriptor(`${descriptorPrefix}widget.partialUpdate`);
43
- // Delete a widget
44
- routes
45
- .delete(`/:id`, widgetController.deleteWidget)
46
- .descriptor(`${descriptorPrefix}widget.delete`);
47
- // Get dynamic collection data
48
- routes
49
- .post(
50
- '/collection-data',
51
- validate(widgetValidation.getCollectionData),
52
- widgetController.getCollectionData
53
- )
54
- .descriptor(`${descriptorPrefix}widget.getCollectionData`);
55
-
56
- export default routes;
@@ -1,82 +0,0 @@
1
- import {
2
- Model,
3
- FilterQuery,
4
- QueryOptions,
5
- ProjectionType,
6
- HydratedDocument,
7
- QueryWithHelpers,
8
- } from 'mongoose';
9
- import { EntityType, IModel, ReturnDocument } from '../types';
10
-
11
- // create
12
- export async function create<T extends EntityType>(
13
- Modal: Model<T>,
14
- data: Partial<T>
15
- ): Promise<ReturnDocument> {
16
- const modalInstance = new Modal(data);
17
- return await modalInstance.save();
18
- }
19
- // update
20
- export async function update<T extends EntityType>(
21
- Modal: Model<T>,
22
- query: FilterQuery<EntityType>,
23
- data: Partial<T>
24
- ): Promise<ReturnDocument | undefined> {
25
- await getOne(Modal, query);
26
- const result = await Modal.findOneAndUpdate(query, data, { new: true });
27
- return result || undefined;
28
- }
29
- // soft-delete
30
- export async function remove<T extends EntityType>(
31
- Modal: Model<T>,
32
- query: FilterQuery<EntityType>
33
- ): Promise<ReturnDocument> {
34
- const modalInstance = await getOne(Modal, query);
35
- return await modalInstance.remove();
36
- }
37
- // delete-all
38
- export async function deleteAll<T extends EntityType>(Modal: Model<T>, query: FilterQuery<T>) {
39
- return Modal.deleteMany(query);
40
- }
41
- // get-all
42
- export function getAll<T extends EntityType>(
43
- Modal: Model<T>,
44
- query: FilterQuery<EntityType> = {},
45
- options?: QueryOptions<EntityType>,
46
- projection?: ProjectionType<EntityType>
47
- // eslint-disable-next-line @typescript-eslint/ban-types
48
- ): QueryWithHelpers<Array<T>, T, {}, T> {
49
- return Modal.find(query, projection, options);
50
- }
51
- // list
52
- export async function list<T extends EntityType>(
53
- Modal: IModel<T>,
54
- where: FilterQuery<T>,
55
- options: QueryOptions<T>
56
- ): Promise<ReturnDocument[]> {
57
- try {
58
- const documents = Modal.paginate(where, options);
59
- return documents;
60
- } catch (error) {
61
- throw new Error((error as Error).message);
62
- }
63
- }
64
- // get-one
65
- export async function getOne<T extends EntityType>(
66
- Modal: Model<T>,
67
- query: FilterQuery<EntityType>,
68
- projection?: ProjectionType<EntityType>
69
- ): Promise<HydratedDocument<T>> {
70
- const modalInstance: HydratedDocument<T> | null = await Modal.findOne(
71
- query,
72
- projection
73
- );
74
- if (!modalInstance)
75
- throw new Error(`Record not found ${Modal.name ? `in ${Modal.name}` : ''}`);
76
-
77
- return modalInstance;
78
- }
79
- // bulk-insert
80
- export async function bulkInsert<T extends EntityType>(Modal: Model<T>, docs: T[]): Promise<ReturnDocument[]> {
81
- return await Modal.insertMany(docs);
82
- }
@@ -1,130 +0,0 @@
1
- import {
2
- Document,
3
- Model,
4
- Types,
5
- FilterQuery,
6
- QueryOptions,
7
- HydratedDocument,
8
- } from 'mongoose';
9
- import { ItemsType, WidgetTypes, ItemTypes } from '.';
10
-
11
- export type TypesType = { value: string; label: string };
12
- // export type CollectionItem = {
13
- // title: string;
14
- // collectionName: string;
15
- // filters?: { [key: string]: string };
16
- // searchColumns: string[];
17
- // };
18
- export interface iConfig {
19
- logger: any;
20
- catchAsync: (
21
- fn: any,
22
- modal?: string
23
- ) => (req: any, res: any, next: any) => void;
24
- collections: CollectionItem[];
25
- }
26
- // Collection
27
- export interface IPageSchema extends Document {
28
- name: string;
29
- code: string;
30
- widgets: string[];
31
- }
32
- export interface ISrcSetSchema extends Document {
33
- width: number;
34
- height: number;
35
- screenSize: number;
36
- itemId: typeof Types.ObjectId;
37
- }
38
- export interface IWidgetSchema extends Document {
39
- items: any;
40
- name: string;
41
- code: string;
42
- autoPlay: boolean;
43
- isActive: boolean;
44
- widgetTitle: string;
45
- webPerRow: number;
46
- mobilePerRow: number;
47
- tabletPerRow: number;
48
- itemsType: ItemsType;
49
- widgetType: WidgetTypes;
50
- collectionName: string;
51
- collectionItems: string[];
52
- }
53
- export interface IItemSchema extends Document {
54
- widgetId: typeof Types.ObjectId;
55
- title: string;
56
- altText: string;
57
- link: string;
58
- sequence: number;
59
- itemType: ItemTypes;
60
- img: any;
61
- srcset?: SrcSetItem[];
62
- }
63
- export interface SrcSetItem {
64
- screenSize: number;
65
- width: number;
66
- height: number;
67
- }
68
- // \ End of Collection
69
-
70
- export type CollectionItem = {
71
- title: string;
72
- collectionName: string;
73
- filters?: { [key: string]: string | number | boolean };
74
- searchColumns?: string[];
75
- match?: ObjectType;
76
- project?: ObjectType;
77
- lookup?: ObjectType;
78
- };
79
-
80
- export interface IConfig {
81
- logger: any;
82
- catchAsync: (
83
- fn: any,
84
- modal?: string
85
- ) => (req: any, res: any, next: any) => void;
86
- collections: CollectionItem[];
87
- }
88
-
89
- export type EntityType =
90
- | IWidgetSchema
91
- | IItemSchema
92
- | IPageSchema
93
- | ISrcSetSchema;
94
- export type ReturnDocument = EntityType;
95
- export interface IModel<T> extends Model<T> {
96
- paginate: (
97
- query: FilterQuery<T>,
98
- options?: QueryOptions
99
- ) => Promise<HydratedDocument<ReturnDocument>[]>;
100
- }
101
-
102
- export type ObjectType = {
103
- [key: string]:
104
- | string
105
- | number
106
- | boolean
107
- | null
108
- | undefined
109
- | string[]
110
- | number[]
111
- | ObjectType
112
- | ObjectType[]
113
- | any;
114
- };
115
-
116
- export interface IDefaultValidations {
117
- createdBy: string;
118
- updatedBy: string;
119
- deletedBy: string;
120
- deletedAt: string;
121
- }
122
-
123
- // helper.ts
124
- export interface IWidgetDataSchema {
125
- _id: string;
126
- code: string;
127
- collectionName: string;
128
- collectionItems: string[];
129
- }
130
- export type IWidgetData = { [key: string]: IWidgetDataSchema };
@@ -1,13 +0,0 @@
1
- export enum ItemsType {
2
- Image = 'Image',
3
- }
4
-
5
- export enum WidgetTypes {
6
- FixedCard = 'FixedCard',
7
- Carousel = 'Carousel',
8
- }
9
-
10
- export enum ItemTypes {
11
- Web = 'Web',
12
- Mobile = 'Mobile',
13
- }
@@ -1,30 +0,0 @@
1
- import { NextFunction } from 'express';
2
- import { CollectionItem, IConfig, IRequest, IResponse } from '../types';
3
- import { RESPONSE_CODES, internalServerError, REGEXS } from '../constants';
4
-
5
- export const defaults: IConfig = {
6
- logger: console as any,
7
- catchAsync:
8
- (fn: any, modal = '') =>
9
- (req: IRequest, res: IResponse, next: NextFunction) => {
10
- Promise.resolve(fn(req, res, next)).catch((err) => {
11
- let message = (err as Error).message;
12
- if (message.match(REGEXS.OBJECTID_CAST_FAILED)) {
13
- message = `${modal} not found with given id!`;
14
- }
15
- // this.logger.error(err.message);
16
- res.status(internalServerError).json({
17
- code: RESPONSE_CODES.ERROR,
18
- message,
19
- data: undefined,
20
- });
21
- });
22
- },
23
- collections: [] as CollectionItem[],
24
- };
25
-
26
- export const commonExcludedFields = {
27
- __v: 0,
28
- isDeleted: 0,
29
- deletedAt: 0,
30
- };
@@ -1,133 +0,0 @@
1
- import { Widget } from '../models';
2
- import { commonExcludedFields, defaults } from './defaults';
3
- import {
4
- IWidgetData,
5
- IWidgetDataSchema,
6
- IWidgetSchema,
7
- SrcSetItem,
8
- } from '../types';
9
-
10
- export async function appendCollectionData(widgetData: IWidgetSchema[]) {
11
- // reduce widget data to optimize query
12
- const newData: IWidgetData = widgetData.reduce(
13
- (acc: IWidgetData, widget: IWidgetSchema) => {
14
- if (widget.collectionName) {
15
- acc[widget.code] = {
16
- _id: widget._id,
17
- code: widget.code,
18
- collectionName: widget.collectionName,
19
- collectionItems: widget.collectionItems,
20
- };
21
- }
22
- return acc;
23
- },
24
- {}
25
- );
26
- if (Object.keys(newData).length > 0) {
27
- const aggregationQuery: any = [
28
- {
29
- $match: {
30
- _id: {
31
- $in: Object.values(newData).map(
32
- (item: IWidgetDataSchema) => item._id
33
- ),
34
- },
35
- },
36
- },
37
- {
38
- // Get only the fields that are not excluded
39
- $project: {
40
- _id: 1,
41
- code: 1,
42
- },
43
- },
44
- ];
45
- let collectionConfig, aggregationQueryPiplelines: any[];
46
- Object.keys(newData).forEach((key: string) => {
47
- collectionConfig = defaults.collections.find(
48
- (c) => c.collectionName === newData[key].collectionName
49
- );
50
- // Build piplelines with config
51
- aggregationQueryPiplelines = [
52
- {
53
- $match: {
54
- _id: {
55
- $in: newData[key].collectionItems,
56
- },
57
- ...(collectionConfig?.match || {}),
58
- },
59
- },
60
- {
61
- $project: {
62
- ...commonExcludedFields,
63
- },
64
- },
65
- ];
66
- // add project config if it exists
67
- if (collectionConfig?.project)
68
- aggregationQueryPiplelines.push({
69
- $project: collectionConfig?.project,
70
- });
71
- // add lookup config if it exists
72
- if (collectionConfig?.lookup)
73
- aggregationQueryPiplelines.push({
74
- $lookup: collectionConfig?.lookup,
75
- });
76
- // Build Aggregation Query
77
- aggregationQuery.push({
78
- $lookup: {
79
- from: newData[key].collectionName,
80
- pipeline: aggregationQueryPiplelines,
81
- as: newData[key].code,
82
- },
83
- });
84
- });
85
- // getting collection data by populating widget
86
- let aggregationData: any = await Widget.aggregate(aggregationQuery);
87
- aggregationData = aggregationData.reduce((acc: any, aggregation: any) => {
88
- acc[aggregation.code] = aggregation[aggregation.code];
89
- return acc;
90
- }, {});
91
- // adding collection data to widgets
92
- return widgetData.map((widget: IWidgetSchema) => {
93
- if (aggregationData[widget.code]) {
94
- return {
95
- ...widget,
96
- collectionItems: aggregationData[widget.code],
97
- };
98
- }
99
- return widget;
100
- });
101
- }
102
- // returning widget data as it is if they do not have dynamic collection
103
- return widgetData;
104
- }
105
-
106
- export function buildSrcSetItem(uri: string, setItem: SrcSetItem) {
107
- const imageItemArr = uri?.split('/') || [];
108
- imageItemArr.splice(
109
- imageItemArr.length - 1,
110
- 0,
111
- `${setItem.width}x${setItem.height}`
112
- );
113
- return imageItemArr.join('/');
114
- }
115
-
116
- export function AddSrcSetsToItems(widgetData: IWidgetSchema) {
117
- if (Array.isArray(widgetData.items) && widgetData.items.length > 0) {
118
- widgetData.items.forEach((item) => {
119
- if (Array.isArray(item.srcset) && item.srcset.length > 0 && item.image) {
120
- item.srcSets = item.srcset.reduce(
121
- (strArr: string[], setItem: SrcSetItem) => {
122
- const imageUri = buildSrcSetItem(item.image.uri, setItem);
123
- strArr.push(`${imageUri} ${setItem.screenSize}w`);
124
- return strArr;
125
- },
126
- []
127
- );
128
-
129
- item.srcSets = item.srcSets.join(', ');
130
- }
131
- });
132
- }
133
- }
@@ -1,54 +0,0 @@
1
- import { RESPONSE_CODES, validationError, success, create } from '../constants';
2
- import { IResponse } from '../types';
3
-
4
- export const failureResponse = (data: any, res: IResponse) => {
5
- let i = 0;
6
- if (data.name === 'ValidationError') {
7
- Object.keys(data.errors).forEach((key) => {
8
- if (i !== 1) {
9
- data.message = data.errors[key].message;
10
- }
11
- i++;
12
- });
13
- }
14
- res.message = data.message;
15
- return res.status(validationError).json({
16
- code: RESPONSE_CODES.ERROR,
17
- message: data.message ? data.message : data,
18
- });
19
- };
20
-
21
- export const successResponse = (data: any, res: IResponse) => {
22
- return res.status(success).json({
23
- code: RESPONSE_CODES.DEFAULT,
24
- message: res.message,
25
- data: data,
26
- });
27
- };
28
-
29
- export const createdDocumentResponse = (data: any, res: IResponse) => {
30
- return res.status(create).json({
31
- code: RESPONSE_CODES.DEFAULT,
32
- message: res.message,
33
- data: data,
34
- });
35
- };
36
-
37
- export const recordNotFound = (res: IResponse) => {
38
- return res.status(success).json({
39
- code: RESPONSE_CODES.DEFAULT,
40
- message: res.message,
41
- data: {},
42
- });
43
- };
44
-
45
- export const inValidParam = (message: any, res: IResponse) => {
46
- /* eslint-disable no-useless-escape */
47
- message = message.replace(/\"/g, '');
48
- res.message = message;
49
- return res.status(validationError).json({
50
- code: RESPONSE_CODES.ERROR,
51
- message: message,
52
- data: undefined,
53
- });
54
- };
@@ -1,22 +0,0 @@
1
- import { ValidationError } from 'joi';
2
- import { NextFunction } from 'express';
3
- import { IRequest, IResponse } from './../types';
4
-
5
- import { defaults } from './defaults';
6
- import { inValidParam, failureResponse } from './responseHandlers';
7
-
8
- const validate = (validator: any) => {
9
- return async function (req: IRequest, res: IResponse, next: NextFunction) {
10
- try {
11
- req.body = await validator.validateAsync(req.body);
12
- next();
13
- } catch (err) {
14
- defaults.logger.error('ValidationError', err);
15
- if ((err as ValidationError).isJoi)
16
- inValidParam((err as Error).message, res);
17
- else failureResponse((err as Error).message, res);
18
- }
19
- };
20
- };
21
-
22
- export default validate;
@@ -1,51 +0,0 @@
1
- import joi from 'joi';
2
- import { IItemSchema, IDefaultValidations, ItemTypes } from '../../types';
3
-
4
- type ItemValidation = IItemSchema & IDefaultValidations;
5
-
6
- const srcset = joi.object().keys({
7
- screenSize: joi.number().required(),
8
- width: joi.number().required(),
9
- height: joi.number().required(),
10
- });
11
-
12
- export const create = joi.object<ItemValidation>({
13
- widgetId: joi.string().required(),
14
- title: joi.string().required(),
15
- altText: joi.string().optional(),
16
- link: joi.string().required(),
17
- sequence: joi.number().optional(),
18
- srcset: joi.array().items(srcset),
19
- img: joi.string().allow(null).optional(),
20
- itemType: joi
21
- .string()
22
- .valid(...Object.values(ItemTypes))
23
- .optional()
24
- .default(ItemTypes.Web),
25
- createdBy: joi.any().optional(),
26
- updatedBy: joi.any().optional(),
27
- deletedBy: joi.any().optional(),
28
- deletedAt: joi.any().optional(),
29
- });
30
-
31
- export const update = joi.object<ItemValidation>({
32
- widgetId: joi.string().required(),
33
- title: joi.string().required(),
34
- altText: joi.string().optional(),
35
- link: joi.string().required(),
36
- sequence: joi.number().optional(),
37
- img: joi.string().allow(null).optional(),
38
- srcset: joi.array().items(srcset),
39
- itemType: joi
40
- .string()
41
- .valid(...Object.values(ItemTypes))
42
- .optional(),
43
- createdBy: joi.any().optional(),
44
- updatedBy: joi.any().optional(),
45
- deletedBy: joi.any().optional(),
46
- deletedAt: joi.any().optional(),
47
- });
48
-
49
- export const list = joi.object({
50
- search: joi.string().allow('').replace(/\s+/g, '_').default(''),
51
- });
@@ -1,59 +0,0 @@
1
- import joi from 'joi';
2
- import { Page } from '../../models';
3
- import { getOne } from '../../services/dbService';
4
- import { VALIDATION } from '../../constants';
5
- import { IPageSchema, IDefaultValidations } from '../../types';
6
-
7
- type PageValidation = IPageSchema & IDefaultValidations;
8
-
9
- const checkUnique = async (value: string): Promise<void> => {
10
- let result;
11
- try {
12
- // throws error if document not found
13
- result = await getOne(Page, {
14
- code: value,
15
- });
16
- // eslint-disable-next-line no-empty
17
- } catch (e) {}
18
- if (result) {
19
- throw new Error(VALIDATION.WIDGET_EXISTS);
20
- }
21
- };
22
-
23
- export const create = joi.object<PageValidation>({
24
- name: joi.string().required(),
25
- code: joi
26
- .string()
27
- .uppercase()
28
- .replace(/\s+/g, '_')
29
- .external(checkUnique)
30
- .required(),
31
- widgets: joi.array().items(joi.string()).optional(),
32
- createdBy: joi.any().optional(),
33
- updatedBy: joi.any().optional(),
34
- deletedBy: joi.any().optional(),
35
- deletedAt: joi.any().optional(),
36
- });
37
-
38
- export const update = joi.object<PageValidation>({
39
- name: joi.string().optional(),
40
- widgets: joi.array().items(joi.string()).optional(),
41
- createdBy: joi.any().optional(),
42
- updatedBy: joi.any().optional(),
43
- deletedBy: joi.any().optional(),
44
- deletedAt: joi.any().optional(),
45
- });
46
-
47
- export const list = joi.object({
48
- search: joi.string().allow('').replace(/\s+/g, '_').optional().default(''),
49
- options: joi
50
- .object({
51
- // sort: joi.alternatives().try(joi.object(), joi.string()).optional(),
52
- populate: joi.array().items().optional().default([]),
53
- offset: joi.number().optional(),
54
- page: joi.number().optional(),
55
- limit: joi.number().optional(),
56
- pagination: joi.boolean().default(false),
57
- })
58
- .default({}),
59
- });