Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Synonym-field-added #56

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@knovator/masters-node",
"version": "2.3.0",
"version": "2.4.0",
"license": "MIT",
"author": "knovator (https://knovator.com/)",
"description": "NodeJS backend for @knovator/masters",
Expand Down
45 changes: 43 additions & 2 deletions src/controllers/masterController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,22 @@ import {
createDocument,
getDocumentByQuery,
} from '../helpers/dbService';
import { mergeSubmastersFunc } from '../helpers/utils';

const catchAsync = (fn: any) => {
return defaults.catchAsync(fn);
};

export const createMaster = catchAsync(async (req: any, res: any) => {
const { mergeSubmasters = [], synonym = [], ...restBody } = req.body;
const mergeSubmastersID = mergeSubmasters.map(
(submaster: any) => submaster.value
);
let mergedSynonyms = await mergeSubmastersFunc(mergeSubmastersID, Master);
mergedSynonyms = [...mergedSynonyms, ...synonym];
const data = new Master({
...req.body,
...restBody,
synonym: mergedSynonyms,
});
if (data.parentId && data.isDefault) {
await bulkUpdate(
Expand All @@ -33,6 +41,18 @@ export const createMaster = catchAsync(async (req: any, res: any) => {
const result = await Master.populate(masterData, [
{ path: 'img', select: 'uri' },
]);

if (mergeSubmastersID.length > 0) {
try {
await Master.deleteMany({ _id: { $in: mergeSubmastersID } });
defaults.onMastersMerged(mergeSubmastersID, masterData._id.toString());
} catch (error) {
throw new Error(
`Failed to delete mergeSubmasters: ${(error as Error).message}`
);
}
}

if (result) {
let section = result.parentCode ? 'submaster' : 'master';
res.message = req?.i18n?.t(`${section}.create`);
Expand All @@ -41,8 +61,17 @@ export const createMaster = catchAsync(async (req: any, res: any) => {
});

export const updateMaster = catchAsync(async (req: any, res: any) => {
const { mergeSubmasters = [], synonym = [], ...restBody } = req.body;
const mergeSubmastersID = mergeSubmasters.map(
(submaster: any) => submaster.value
);
let mergedSynonyms = await mergeSubmastersFunc(mergeSubmastersID, Master);
mergedSynonyms = [...mergedSynonyms, ...synonym];
const data = {
...restBody,
synonym: mergedSynonyms,
};
const id = req.params.id;
const data = req.body;
if (data.isDefault) {
// checking if data contains isDefault, if contains, reset all defaults
const masterData: any = await getDocumentByQuery(Master, { _id: id });
Expand All @@ -63,6 +92,16 @@ export const updateMaster = catchAsync(async (req: any, res: any) => {
{ new: true },
{ path: 'img', select: 'uri' }
);
if (mergeSubmastersID?.length > 0) {
try {
await Master.deleteMany({ _id: { $in: mergeSubmastersID } });
defaults.onMastersMerged(mergeSubmastersID, id);
} catch (error) {
throw new Error(
`Failed to delete mergeSubmasters: ${(error as Error).message}`
);
}
}
const result = await Master.findOne({ _id: id });
if (result) {
let section = result.parentCode ? 'submaster' : 'master';
Expand Down Expand Up @@ -165,6 +204,7 @@ export const deleteMaster = catchAsync(async (req: any, res: any) => {
export const listMaster = catchAsync(async (req: any, res: any) => {
let { page, limit, sort, populate } = req.body.options;
const isCountOnly = req.body.isCountOnly || false;
const exclude = req.body.exclude;
const search = req.body.search || '';
const customQuery = req.body.query || {};
let sortMaster = sort ? sort : { seq: 1 };
Expand All @@ -191,6 +231,7 @@ export const listMaster = catchAsync(async (req: any, res: any) => {
customOptions,
isCountOnly,
search,
exclude,
customQuery,
isActive === null ? [true, false] : [isActive],
populate,
Expand Down
1 change: 1 addition & 0 deletions src/helpers/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { RESPONSE_CODE, internalServerError } from "../constants/common";

export default {
logger: console,
onMastersMerged: (_removedMasterIds: string[], _newMasterId: string) => {},
catchAsync: function (fn: any) {
return function (req: any, res: any, next: any) {
Promise.resolve(fn(req, res, next)).catch((err) => {
Expand Down
22 changes: 22 additions & 0 deletions src/helpers/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export async function mergeSubmastersFunc(mergeSubmastersID: object, Master: any) {
const submasters = await Master.find({ _id: { $in: mergeSubmastersID } }).select('names name');

const namesSet: Set<string> = new Set();

submasters.forEach((submaster: any) => {
if (submaster.names) {
Object.values(submaster.names || {}).forEach((masterName) => {
namesSet.add(masterName as string);
});
}

if (submaster.name) {
namesSet.add(submaster.name);
}
});

const namesArr = Array.from(namesSet);

return namesArr;
}

2 changes: 2 additions & 0 deletions src/helpers/validations/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ export default joi
deletedBy: joi.object().optional(),
deletedAt: joi.date().optional(),
isActive: joi.boolean().default(true),
synonym: joi.array().optional(),
mergeSubmasters: joi.array().optional()
})
.custom(async (obj) => {
const { parentId, code } = obj;
Expand Down
1 change: 1 addition & 0 deletions src/helpers/validations/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import joi from 'joi';
export default joi
.object({
language: joi.string().optional(),
exclude: joi.string().optional(),
search: joi.string().allow('').default(''),
query: joi
.object({
Expand Down
2 changes: 2 additions & 0 deletions src/helpers/validations/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,7 @@ export default joi
seq: joi.number().optional(),
updatedBy: joi.object().optional(),
extra: joi.string().optional(),
synonym: joi.array().optional(),
mergeSubmasters: joi.array().optional()
})
.unknown(false);
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ interface MastersProps {
preDelete: (_record: any) => Promise<{}>;
postUpdate: (_record: any) => Promise<{}>;
languages: LanguageType[];
onMastersMerged: any
}

export function masters({
Expand All @@ -18,7 +19,9 @@ export function masters({
preDelete,
postUpdate,
languages,
onMastersMerged
}: Partial<MastersProps> = defaults) {
if (typeof onMastersMerged === 'function') defaults.onMastersMerged = onMastersMerged
if (typeof catchAsync === 'function') defaults.catchAsync = catchAsync;
if (typeof authentication === 'function')
defaults.authentication = authentication;
Expand Down
1 change: 1 addition & 0 deletions src/models/Master.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export const MasterSchema = new Schema<MasterType>(
createdBy: { type: Schema.Types.ObjectId, ref: 'user' },
updatedBy: [{ type: Schema.Types.ObjectId, ref: 'user' }],
deletedBy: { type: Schema.Types.ObjectId, ref: 'user' },
synonym: [],
},
{ timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' } }
);
Expand Down
10 changes: 10 additions & 0 deletions src/services/master.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export const listMaster = async (
customOptions: any,
isCountOnly: any,
search: any,
exclude: string,
customQuery: any,
onlyActive = [true],
populate: any,
Expand All @@ -88,6 +89,12 @@ export const listMaster = async (
},
},
]),
{
synonym : {
$regex: search,
$options: 'i',
},
},
{
code: {
$regex: search.replace(/\s+/g, '_'),
Expand Down Expand Up @@ -132,6 +139,9 @@ export const listMaster = async (
}
: {}),
};
if (exclude) {
(query as any)._id = { $ne: exclude };
}
let options = {
select: [],
collation: '',
Expand Down
1 change: 1 addition & 0 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ type MasterType = {
createdBy: import('mongoose').ObjectId;
updatedBy: [import('mongoose').ObjectId];
deletedBy: import('mongoose').ObjectId;
synonym: []
};

type EntityType = MasterType;
Expand Down