@avleon/core 0.0.19 → 0.0.24
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.
- package/README.md +559 -2
- package/dist/application.d.ts +26 -0
- package/dist/application.js +50 -0
- package/dist/collection.js +3 -2
- package/dist/container.d.ts +1 -0
- package/dist/container.js +2 -1
- package/dist/environment-variables.js +1 -1
- package/dist/file-storage.js +0 -128
- package/dist/helpers.d.ts +2 -0
- package/dist/helpers.js +41 -4
- package/dist/icore.d.ts +68 -26
- package/dist/icore.js +235 -212
- package/dist/index.d.ts +2 -2
- package/dist/index.js +4 -2
- package/dist/middleware.js +0 -8
- package/dist/multipart.js +4 -1
- package/dist/openapi.d.ts +37 -37
- package/dist/params.js +2 -2
- package/dist/response.js +6 -2
- package/dist/route-methods.js +1 -1
- package/dist/swagger-schema.js +4 -1
- package/dist/testing.js +5 -2
- package/dist/utils/index.d.ts +2 -0
- package/dist/utils/index.js +18 -0
- package/dist/utils/optional-require.d.ts +8 -0
- package/dist/utils/optional-require.js +70 -0
- package/dist/validation.d.ts +4 -1
- package/dist/validation.js +10 -5
- package/package.json +19 -11
- package/src/application.ts +96 -0
- package/src/authentication.ts +16 -0
- package/src/collection.ts +254 -0
- package/src/config.ts +39 -0
- package/src/constants.ts +1 -0
- package/src/container.ts +54 -0
- package/src/controller.ts +128 -0
- package/src/decorators.ts +27 -0
- package/src/environment-variables.ts +46 -0
- package/src/exceptions/http-exceptions.ts +86 -0
- package/src/exceptions/index.ts +1 -0
- package/src/exceptions/system-exception.ts +34 -0
- package/src/file-storage.ts +206 -0
- package/src/helpers.ts +328 -0
- package/src/icore.ts +1064 -0
- package/src/index.ts +30 -0
- package/src/logger.ts +72 -0
- package/src/map-types.ts +159 -0
- package/src/middleware.ts +98 -0
- package/src/multipart.ts +116 -0
- package/src/openapi.ts +372 -0
- package/src/params.ts +111 -0
- package/src/queue.ts +126 -0
- package/src/response.ts +117 -0
- package/src/results.ts +30 -0
- package/src/route-methods.ts +186 -0
- package/src/swagger-schema.ts +213 -0
- package/src/testing.ts +220 -0
- package/src/types/app-builder.interface.ts +19 -0
- package/src/types/application.interface.ts +9 -0
- package/src/utils/hash.ts +5 -0
- package/src/utils/index.ts +2 -0
- package/src/utils/optional-require.ts +50 -0
- package/src/validation.ts +156 -0
- package/src/validator-extend.ts +25 -0
- package/dist/classToOpenapi.d.ts +0 -0
- package/dist/classToOpenapi.js +0 -1
- package/dist/render.d.ts +0 -1
- package/dist/render.js +0 -8
- package/jest.config.ts +0 -9
- package/tsconfig.json +0 -25
- /package/dist/{security.d.ts → utils/hash.d.ts} +0 -0
- /package/dist/{security.js → utils/hash.js} +0 -0
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import fs, { createReadStream, PathLike } from "fs";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import { pipeline } from "stream/promises";
|
|
4
|
+
import {
|
|
5
|
+
BadRequestException,
|
|
6
|
+
InternalErrorException,
|
|
7
|
+
} from "./exceptions/http-exceptions";
|
|
8
|
+
import { MultipartFile } from "./multipart";
|
|
9
|
+
import { AppService } from "./decorators";
|
|
10
|
+
import os from "os";
|
|
11
|
+
import { SystemUseError } from "./exceptions/system-exception";
|
|
12
|
+
import { SavedMultipartFile } from "@fastify/multipart";
|
|
13
|
+
|
|
14
|
+
interface TransformOptions {
|
|
15
|
+
resize?: { width: number; height: number };
|
|
16
|
+
format?: "jpeg" | "png" | "webp" | "avif";
|
|
17
|
+
quality?: number;
|
|
18
|
+
// Add other sharp options as needed
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/*
|
|
22
|
+
//temp file
|
|
23
|
+
files[0].type // "file"
|
|
24
|
+
files[0].filepath
|
|
25
|
+
files[0].fieldname
|
|
26
|
+
files[0].filename
|
|
27
|
+
files[0].encoding
|
|
28
|
+
files[0].mimetype
|
|
29
|
+
files[0].fields
|
|
30
|
+
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/*
|
|
34
|
+
// stream file
|
|
35
|
+
data.file // stream
|
|
36
|
+
data.fields // other parsed parts
|
|
37
|
+
data.fieldname
|
|
38
|
+
data.filename
|
|
39
|
+
data.encoding
|
|
40
|
+
data.mimetype
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
export interface FileStorageInterface {
|
|
44
|
+
transform(options: TransformOptions): FileStorage;
|
|
45
|
+
save(
|
|
46
|
+
file: MultipartFile,
|
|
47
|
+
options?: SaveOptionsSingle
|
|
48
|
+
): Promise<MultipartFile | undefined>;
|
|
49
|
+
saveAll(
|
|
50
|
+
files: MultipartFile[],
|
|
51
|
+
options?: SaveOptions
|
|
52
|
+
): Promise<MultipartFile[] | undefined>;
|
|
53
|
+
|
|
54
|
+
remove(filepath: PathLike): Promise<void>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface SaveOptions {
|
|
58
|
+
overwrite?: boolean;
|
|
59
|
+
to?: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface SaveOptionsSingle extends SaveOptions {
|
|
63
|
+
saveAs?: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
@AppService
|
|
67
|
+
export class FileStorage implements FileStorageInterface {
|
|
68
|
+
private transformOptions: TransformOptions | null = null;
|
|
69
|
+
|
|
70
|
+
transform(options: TransformOptions) {
|
|
71
|
+
this.transformOptions = options;
|
|
72
|
+
return this;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
private isFileExists(fpath: PathLike) {
|
|
76
|
+
return fs.existsSync(fpath);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async save(f: MultipartFile, options?: SaveOptionsSingle) {
|
|
80
|
+
let foptions: SaveOptionsSingle = {
|
|
81
|
+
overwrite: options && options.overwrite ? options.overwrite : true,
|
|
82
|
+
};
|
|
83
|
+
try {
|
|
84
|
+
if (f.type == "file") {
|
|
85
|
+
const fname = path.join(process.cwd(), `public/${f.filename}`);
|
|
86
|
+
|
|
87
|
+
if (!foptions.overwrite && this.isFileExists(fname)) {
|
|
88
|
+
throw new SystemUseError("File already exits.");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
await pipeline(f.file, fs.createWriteStream(fname));
|
|
92
|
+
return f;
|
|
93
|
+
}
|
|
94
|
+
} catch (err) {
|
|
95
|
+
throw new SystemUseError("Can't upload file");
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async remove(filepath: PathLike) {
|
|
100
|
+
if (!this.isFileExists(path.join(process.cwd(), "public/" + filepath))) {
|
|
101
|
+
throw new SystemUseError("File doesn't exists.");
|
|
102
|
+
}
|
|
103
|
+
return fs.unlinkSync(path.join(process.cwd(), "public/" + filepath));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async saveAll(files: MultipartFile[], options?: SaveOptions) {
|
|
107
|
+
try {
|
|
108
|
+
let foptions: SaveOptions = {
|
|
109
|
+
overwrite: options && options.overwrite ? options.overwrite : true,
|
|
110
|
+
};
|
|
111
|
+
for (let f of files) {
|
|
112
|
+
let uploadPath = `public`;
|
|
113
|
+
if (options?.to) {
|
|
114
|
+
uploadPath = `public/${options.to}`;
|
|
115
|
+
}
|
|
116
|
+
const fname = path.join(process.cwd(), `${uploadPath}/${f.filename}`);
|
|
117
|
+
await this.ensureDirectoryExists(fname);
|
|
118
|
+
if (f.file) {
|
|
119
|
+
await pipeline(f.file, fs.createWriteStream(fname));
|
|
120
|
+
} else {
|
|
121
|
+
const fp = f as SavedMultipartFile;
|
|
122
|
+
await pipeline(
|
|
123
|
+
fs.createReadStream(fp.filepath),
|
|
124
|
+
fs.createWriteStream(fname)
|
|
125
|
+
);
|
|
126
|
+
fs.unlinkSync(fp.filepath);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return files;
|
|
130
|
+
} catch (error) {
|
|
131
|
+
console.error(error);
|
|
132
|
+
throw new SystemUseError("Can't upload file");
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
private async processImage(
|
|
137
|
+
fileStream: NodeJS.ReadableStream,
|
|
138
|
+
outputPath: string
|
|
139
|
+
) {
|
|
140
|
+
try {
|
|
141
|
+
const sharp = await import("sharp"); // Lazy import sharp
|
|
142
|
+
|
|
143
|
+
let sharpPipeline = sharp.default();
|
|
144
|
+
|
|
145
|
+
if (this.transformOptions?.resize) {
|
|
146
|
+
sharpPipeline = sharpPipeline.resize(
|
|
147
|
+
this.transformOptions.resize.width,
|
|
148
|
+
this.transformOptions.resize.height
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (this.transformOptions?.format) {
|
|
153
|
+
switch (this.transformOptions.format) {
|
|
154
|
+
case "jpeg":
|
|
155
|
+
sharpPipeline = sharpPipeline.jpeg({
|
|
156
|
+
quality: this.transformOptions.quality || 80,
|
|
157
|
+
});
|
|
158
|
+
break;
|
|
159
|
+
case "png":
|
|
160
|
+
sharpPipeline = sharpPipeline.png({
|
|
161
|
+
quality: this.transformOptions.quality || 80,
|
|
162
|
+
});
|
|
163
|
+
break;
|
|
164
|
+
case "webp":
|
|
165
|
+
sharpPipeline = sharpPipeline.webp({
|
|
166
|
+
quality: this.transformOptions.quality || 80,
|
|
167
|
+
});
|
|
168
|
+
break;
|
|
169
|
+
case "avif":
|
|
170
|
+
sharpPipeline = sharpPipeline.avif({
|
|
171
|
+
quality: this.transformOptions.quality || 80,
|
|
172
|
+
});
|
|
173
|
+
break;
|
|
174
|
+
default:
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
await pipeline(
|
|
180
|
+
fileStream,
|
|
181
|
+
sharpPipeline,
|
|
182
|
+
fs.createWriteStream(outputPath)
|
|
183
|
+
);
|
|
184
|
+
} catch (error: any) {
|
|
185
|
+
if (
|
|
186
|
+
error.code === "MODULE_NOT_FOUND" &&
|
|
187
|
+
error.message.includes("sharp")
|
|
188
|
+
) {
|
|
189
|
+
throw new InternalErrorException(
|
|
190
|
+
"sharp module not found. Please install sharp to use image transformations."
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
console.error("Image processing failed:", error);
|
|
194
|
+
throw new InternalErrorException("Image processing failed.");
|
|
195
|
+
} finally {
|
|
196
|
+
this.transformOptions = null; // Reset transform options after processing
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
private async ensureDirectoryExists(filePath: string) {
|
|
201
|
+
const dir = path.dirname(filePath);
|
|
202
|
+
if (!fs.existsSync(dir)) {
|
|
203
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
package/src/helpers.ts
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright 2024
|
|
3
|
+
* @author Tareq Hossain
|
|
4
|
+
* @email xtrinsic96@gmail.com
|
|
5
|
+
* @url https://github.com/xtareq
|
|
6
|
+
*/
|
|
7
|
+
import { instanceToPlain, plainToInstance } from "class-transformer";
|
|
8
|
+
import { InternalErrorException } from "./exceptions";
|
|
9
|
+
import fs from "fs";
|
|
10
|
+
import container from "./container";
|
|
11
|
+
import { SystemUseError } from "./exceptions/system-exception";
|
|
12
|
+
import crypto, { UUID } from "crypto";
|
|
13
|
+
import { getMetadataStorage, validate, validateSync } from "class-validator";
|
|
14
|
+
|
|
15
|
+
export const uuid = crypto.randomUUID();
|
|
16
|
+
|
|
17
|
+
export function inject<T>(cls: new (...args: any[]) => T): T {
|
|
18
|
+
try {
|
|
19
|
+
return container.get(cls);
|
|
20
|
+
} catch (error) {
|
|
21
|
+
throw new SystemUseError(
|
|
22
|
+
`Not a project class. Maybe you wanna register it first.`
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export type Constructor<T = any> = new (...args: any[]) => T;
|
|
28
|
+
|
|
29
|
+
export function isConstructor(func: any): boolean {
|
|
30
|
+
|
|
31
|
+
if (typeof func !== "function") {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (func === Function.prototype.bind || func instanceof RegExp) {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (func.prototype && typeof func.prototype === "object") {
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
try {
|
|
44
|
+
const instance = new (func as any)();
|
|
45
|
+
return typeof instance === "object";
|
|
46
|
+
} catch (e) {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function formatUrl(path: string): string {
|
|
52
|
+
if (typeof path !== "string") {
|
|
53
|
+
throw new Error("The path must be a string");
|
|
54
|
+
}
|
|
55
|
+
path = path.trim();
|
|
56
|
+
|
|
57
|
+
if (!path.startsWith("/")) {
|
|
58
|
+
path = "/" + path;
|
|
59
|
+
}
|
|
60
|
+
path = path.replace(/\/\/+/g, "/");
|
|
61
|
+
if (path.endsWith("/")) {
|
|
62
|
+
path = path.slice(0, -1);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return path;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function parsedPath(ipath: string): string {
|
|
69
|
+
return !ipath.startsWith("/") ? "/" + ipath : ipath;
|
|
70
|
+
}
|
|
71
|
+
export const isClassValidator = (target: Constructor) => {
|
|
72
|
+
try {
|
|
73
|
+
const clsval = require("class-validator");
|
|
74
|
+
const result = getMetadataStorage().getTargetValidationMetadatas(
|
|
75
|
+
target,
|
|
76
|
+
"",
|
|
77
|
+
false,
|
|
78
|
+
false
|
|
79
|
+
);
|
|
80
|
+
return result.length > 0;
|
|
81
|
+
} catch (err: any) {
|
|
82
|
+
console.log(err);
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
export interface MatchLocation {
|
|
88
|
+
line: number;
|
|
89
|
+
column: number;
|
|
90
|
+
}
|
|
91
|
+
export const getLineNumber = (
|
|
92
|
+
filePath: string,
|
|
93
|
+
rpath: string | RegExp
|
|
94
|
+
): MatchLocation[] | null => {
|
|
95
|
+
let numbers = [];
|
|
96
|
+
try {
|
|
97
|
+
const fileContent = fs.readFileSync(filePath, "utf8");
|
|
98
|
+
const lines = fileContent.split("\n");
|
|
99
|
+
for (let i = 0; i < lines.length; i++) {
|
|
100
|
+
const match = lines[i].match(rpath);
|
|
101
|
+
|
|
102
|
+
if (match) {
|
|
103
|
+
console.log(match);
|
|
104
|
+
numbers.push({
|
|
105
|
+
line: i + 1,
|
|
106
|
+
column: match.index ?? 0,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return numbers;
|
|
112
|
+
} catch (error) {
|
|
113
|
+
return numbers;
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
export function normalizePath(base: string = "/", subPath: string = "/") {
|
|
118
|
+
return `/${base}/${subPath}`.replace(/\/+/g, "/").replace(/\/$/, "");
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function extrctParamFromUrl(url: string) {
|
|
122
|
+
const splitPart = url
|
|
123
|
+
.split("/")
|
|
124
|
+
.filter((x) => x.startsWith(":") || x.startsWith("?:"));
|
|
125
|
+
return splitPart.map((f) => ({
|
|
126
|
+
key: f.replace(/(\?|:)/g, ""),
|
|
127
|
+
required: !f.startsWith("?:"),
|
|
128
|
+
}));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function findDuplicates(arr: string[]): string[] {
|
|
132
|
+
const seen = new Set();
|
|
133
|
+
const duplicates = new Set();
|
|
134
|
+
|
|
135
|
+
for (const str of arr) {
|
|
136
|
+
if (seen.has(str)) {
|
|
137
|
+
duplicates.add(str);
|
|
138
|
+
} else {
|
|
139
|
+
seen.add(str);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return Array.from(duplicates) as string[];
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function getDataType(expectedType: any) {
|
|
147
|
+
switch (expectedType.name) {
|
|
148
|
+
case "Object":
|
|
149
|
+
if (Array.isArray(expectedType)) {
|
|
150
|
+
return "array";
|
|
151
|
+
}
|
|
152
|
+
return "object";
|
|
153
|
+
case "String":
|
|
154
|
+
return "string";
|
|
155
|
+
case "Number":
|
|
156
|
+
return "number";
|
|
157
|
+
case "Boolean":
|
|
158
|
+
return "boolean";
|
|
159
|
+
default:
|
|
160
|
+
return expectedType;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
export function isValidType(value: any, expectedType: any): boolean {
|
|
164
|
+
if (value === undefined || value === null) return true;
|
|
165
|
+
|
|
166
|
+
switch (expectedType.name) {
|
|
167
|
+
case "String":
|
|
168
|
+
return typeof value === "string";
|
|
169
|
+
case "Number":
|
|
170
|
+
return typeof value === "number" || !isNaN(Number(value));
|
|
171
|
+
case "Boolean":
|
|
172
|
+
return typeof value === "boolean";
|
|
173
|
+
default:
|
|
174
|
+
return value instanceof expectedType;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function isValidJsonString(value: string): object | boolean {
|
|
179
|
+
try {
|
|
180
|
+
return JSON.parse(value);
|
|
181
|
+
} catch (err: any) {
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function jsonToJs(value: string) {
|
|
187
|
+
try {
|
|
188
|
+
return JSON.parse(value);
|
|
189
|
+
} catch (err: any) {
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function jsonToInstance(value: string, instance: Constructor) {
|
|
195
|
+
try {
|
|
196
|
+
const parsedValue = JSON.parse(value);
|
|
197
|
+
return plainToInstance(instance, parsedValue);
|
|
198
|
+
} catch (err: any) {
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export function transformObjectByInstanceToObject(
|
|
204
|
+
instance: Constructor,
|
|
205
|
+
value: object
|
|
206
|
+
) {
|
|
207
|
+
return instanceToPlain(plainToInstance(instance, value), {
|
|
208
|
+
excludeExtraneousValues: true,
|
|
209
|
+
exposeUnsetFields: true,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export const isClassValidatorClass = (target: Constructor) => {
|
|
214
|
+
try {
|
|
215
|
+
const clsval = require("class-validator");
|
|
216
|
+
const result = clsval
|
|
217
|
+
.getMetadataStorage()
|
|
218
|
+
.getTargetValidationMetadatas(target, undefined, false, false);
|
|
219
|
+
return result.length > 0;
|
|
220
|
+
} catch (err: any) {
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
export async function validateObjectByInstance(
|
|
226
|
+
target: Constructor,
|
|
227
|
+
value: object = {},
|
|
228
|
+
options: "object" | "array" = "array"
|
|
229
|
+
) {
|
|
230
|
+
try {
|
|
231
|
+
const { validateOrReject } = require("class-validator");
|
|
232
|
+
const { plainToInstance } = require("class-transformer");
|
|
233
|
+
await validateOrReject(plainToInstance(target, value));
|
|
234
|
+
} catch (error: any) {
|
|
235
|
+
if (typeof error == "object" && Array.isArray(error)) {
|
|
236
|
+
const errors =
|
|
237
|
+
options == "object"
|
|
238
|
+
? error.reduce((acc: any, x: any) => {
|
|
239
|
+
//acc[x.property] = Object.values(x.constraints);
|
|
240
|
+
acc[x.property] = x.constraints;
|
|
241
|
+
return acc;
|
|
242
|
+
}, {})
|
|
243
|
+
: error.map((x) => ({
|
|
244
|
+
path: x.property,
|
|
245
|
+
constraints: x.constraints,
|
|
246
|
+
}));
|
|
247
|
+
return errors;
|
|
248
|
+
} else {
|
|
249
|
+
throw new InternalErrorException("Can't validate object");
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
type ValidationError = {
|
|
255
|
+
count: number;
|
|
256
|
+
errors: any;
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
export function validateRequestBody(
|
|
260
|
+
target: Constructor,
|
|
261
|
+
value: object,
|
|
262
|
+
options: "object" | "array" = "array"
|
|
263
|
+
): ValidationError {
|
|
264
|
+
if (!isClassValidatorClass(target)) return { count: 0, errors: {} };
|
|
265
|
+
const error = validateSync(plainToInstance(target, value ? value : {}));
|
|
266
|
+
const errors =
|
|
267
|
+
options == "object"
|
|
268
|
+
? error.reduce((acc: any, x: any) => {
|
|
269
|
+
//acc[x.property] = Object.values(x.constraints);
|
|
270
|
+
acc[x.property] = x.constraints;
|
|
271
|
+
return acc;
|
|
272
|
+
}, {})
|
|
273
|
+
: error.map((x) => ({ path: x.property, constraints: x.constraints }));
|
|
274
|
+
return { count: error.length, errors } as ValidationError;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export function pick<T extends object>(obj: T, paths: string[]): Partial<T> {
|
|
278
|
+
const result: any = {};
|
|
279
|
+
|
|
280
|
+
for (const path of paths) {
|
|
281
|
+
const keys = path.split(".");
|
|
282
|
+
let source: any = obj;
|
|
283
|
+
let target: any = result;
|
|
284
|
+
|
|
285
|
+
for (let i = 0; i < keys.length; i++) {
|
|
286
|
+
const key = keys[i];
|
|
287
|
+
|
|
288
|
+
if (!(key in source)) break;
|
|
289
|
+
|
|
290
|
+
if (i === keys.length - 1) {
|
|
291
|
+
target[key] = source[key];
|
|
292
|
+
} else {
|
|
293
|
+
source = source[key];
|
|
294
|
+
target[key] = target[key] || {};
|
|
295
|
+
target = target[key];
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
return result;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
export function exclude<T extends object>(
|
|
305
|
+
obj: T | T[],
|
|
306
|
+
paths: string[],
|
|
307
|
+
): Partial<T> | Partial<T>[] {
|
|
308
|
+
if (Array.isArray(obj)) {
|
|
309
|
+
return obj.map((item) => exclude(item, paths) as Partial<T>);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const clone = structuredClone(obj); // Or use lodash.cloneDeep
|
|
313
|
+
for (const path of paths) {
|
|
314
|
+
const keys = path.split(".");
|
|
315
|
+
let target: any = clone;
|
|
316
|
+
|
|
317
|
+
for (let i = 0; i < keys.length - 1; i++) {
|
|
318
|
+
if (!(keys[i] in target)) break;
|
|
319
|
+
target = target[keys[i]];
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
delete target?.[keys[keys.length - 1]];
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
return clone;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
|