@dexyn/common-library 1.0.5 → 1.0.8

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,25 @@
1
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
2
+ export interface ApiOptions {
3
+ method?: HttpMethod;
4
+ headers?: Record<string, string>;
5
+ body?: unknown;
6
+ }
7
+ /**
8
+ * A functional API client that requires a base URL upon creation.
9
+ * Provides utility functions for making HTTP requests with query parameters,
10
+ * custom HTTP methods, headers, and request bodies.
11
+ */
12
+ export declare const createApiClient: (basePath: string) => {
13
+ get: <T>(endpoint: string, queryParameters?: Record<string, string | number | boolean | null | undefined>) => Promise<T>;
14
+ post: <T>(endpoint: string, body?: unknown) => Promise<T>;
15
+ put: <T>(endpoint: string, body?: unknown) => Promise<T>;
16
+ delete: <T>(endpoint: string) => Promise<T>;
17
+ };
18
+ export declare const ApiClientUtils: {
19
+ createApiClient: (basePath: string) => {
20
+ get: <T>(endpoint: string, queryParameters?: Record<string, string | number | boolean | null | undefined>) => Promise<T>;
21
+ post: <T>(endpoint: string, body?: unknown) => Promise<T>;
22
+ put: <T>(endpoint: string, body?: unknown) => Promise<T>;
23
+ delete: <T>(endpoint: string) => Promise<T>;
24
+ };
25
+ };
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ApiClientUtils = exports.createApiClient = void 0;
4
+ /**
5
+ * A functional API client that requires a base URL upon creation.
6
+ * Provides utility functions for making HTTP requests with query parameters,
7
+ * custom HTTP methods, headers, and request bodies.
8
+ */
9
+ const createApiClient = (basePath) => {
10
+ if (!basePath) {
11
+ throw new Error('Base path is required');
12
+ }
13
+ const sanitizedBasePath = basePath.replace(/\/$/, '');
14
+ const request = async (endpoint, options = {}, queryParameters = {}) => {
15
+ const { method = 'GET', headers, body } = options;
16
+ // Construct query string from queryParameters
17
+ const queryString = new URLSearchParams(Object.entries(queryParameters).reduce((acc, [key, value]) => {
18
+ if (value !== undefined) {
19
+ acc[key] = String(value);
20
+ }
21
+ return acc;
22
+ }, {})).toString();
23
+ // Append query string to endpoint if queryParameters exist
24
+ const url = queryString ? `${sanitizedBasePath}/${endpoint}?${queryString}` : `${sanitizedBasePath}/${endpoint}`;
25
+ if (method === 'GET' && body) {
26
+ throw new Error('GET requests cannot have a body');
27
+ }
28
+ const requestBody = body ? JSON.stringify(body) : undefined;
29
+ const response = await fetch(url, {
30
+ method,
31
+ headers: {
32
+ 'Content-Type': 'application/json',
33
+ ...headers,
34
+ },
35
+ body: requestBody,
36
+ });
37
+ if (!response.ok) {
38
+ const errorData = await response.json();
39
+ throw new Error(`Request failed with status ${response.status}: ${JSON.stringify(errorData)}`);
40
+ }
41
+ return await response.json();
42
+ };
43
+ return {
44
+ get: (endpoint, queryParameters = {}) => request(endpoint, { method: 'GET' }, queryParameters),
45
+ post: (endpoint, body) => request(endpoint, { method: 'POST', body }),
46
+ put: (endpoint, body) => request(endpoint, { method: 'PUT', body }),
47
+ delete: (endpoint) => request(endpoint, { method: 'DELETE' }),
48
+ };
49
+ };
50
+ exports.createApiClient = createApiClient;
51
+ exports.ApiClientUtils = { createApiClient: exports.createApiClient };
@@ -8,4 +8,8 @@
8
8
  * DateFormatter.formatTime(new Date("2024-12-03T10:30:00"), "en-US", { hour: "2-digit", minute: "2-digit" });
9
9
  * // Output: "10:30 AM"
10
10
  */
11
- export declare function formatDateTime(date: Date, locale?: string, options?: Intl.DateTimeFormatOptions): string;
11
+ declare function formatDateTime(date: Date, locale?: string, options?: Intl.DateTimeFormatOptions): string;
12
+ declare const DateUtils: {
13
+ formatDateTime: typeof formatDateTime;
14
+ };
15
+ export { DateUtils };
package/date/dateUtils.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.formatDateTime = formatDateTime;
3
+ exports.DateUtils = void 0;
4
4
  /**
5
5
  * Formats a date as a time string.
6
6
  * @param date The `Date` object to format.
@@ -14,3 +14,7 @@ exports.formatDateTime = formatDateTime;
14
14
  function formatDateTime(date, locale = "en-US", options = { hour: "numeric", minute: "numeric", second: "numeric" }) {
15
15
  return new Intl.DateTimeFormat(locale, options).format(date);
16
16
  }
17
+ const DateUtils = {
18
+ formatDateTime
19
+ };
20
+ exports.DateUtils = DateUtils;
package/index.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { ErrorResult, StandardError, Result, ErrorName } from "./result/resultUtils";
2
+ export { ResultUtils } from "./result/resultUtils";
3
+ export { HttpResultUtils } from "./result/httpResultUtils";
4
+ export { DateUtils } from "./date/dateUtils";
5
+ export { ValidationUtils } from "./validation/validationUtils";
6
+ export { ApiClientUtils } from "./api/apiClientUtils";
7
+ export type { ErrorResult, StandardError, Result, ErrorName };
package/index.js ADDED
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ApiClientUtils = exports.ValidationUtils = exports.DateUtils = exports.HttpResultUtils = exports.ResultUtils = void 0;
4
+ var resultUtils_1 = require("./result/resultUtils");
5
+ Object.defineProperty(exports, "ResultUtils", { enumerable: true, get: function () { return resultUtils_1.ResultUtils; } });
6
+ var httpResultUtils_1 = require("./result/httpResultUtils");
7
+ Object.defineProperty(exports, "HttpResultUtils", { enumerable: true, get: function () { return httpResultUtils_1.HttpResultUtils; } });
8
+ var dateUtils_1 = require("./date/dateUtils");
9
+ Object.defineProperty(exports, "DateUtils", { enumerable: true, get: function () { return dateUtils_1.DateUtils; } });
10
+ var validationUtils_1 = require("./validation/validationUtils");
11
+ Object.defineProperty(exports, "ValidationUtils", { enumerable: true, get: function () { return validationUtils_1.ValidationUtils; } });
12
+ var apiClientUtils_1 = require("./api/apiClientUtils");
13
+ Object.defineProperty(exports, "ApiClientUtils", { enumerable: true, get: function () { return apiClientUtils_1.ApiClientUtils; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dexyn/common-library",
3
- "version": "1.0.5",
3
+ "version": "1.0.8",
4
4
  "main": "index.js",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,10 +1,13 @@
1
1
  import { ErrorResult } from "./resultUtils";
2
- export declare const HttpResult: {
3
- Accepted: () => {
4
- status: number;
5
- };
6
- BadRequest: (error: ErrorResult) => {
7
- status: number;
8
- jsonBody: string;
9
- };
2
+ declare function Accepted(): {
3
+ status: number;
10
4
  };
5
+ declare function BadRequest(error: ErrorResult): {
6
+ status: number;
7
+ jsonBody: string;
8
+ };
9
+ export declare const HttpResultUtils: {
10
+ Accepted: typeof Accepted;
11
+ BadRequest: typeof BadRequest;
12
+ };
13
+ export {};
@@ -1,18 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpResult = void 0;
4
- const createHTTPResult = () => {
5
- function Accepted() {
6
- return {
7
- status: 202,
8
- };
9
- }
10
- function BadRequest(error) {
11
- return {
12
- status: 400,
13
- jsonBody: JSON.stringify(error)
14
- };
15
- }
16
- return { Accepted, BadRequest };
17
- };
18
- exports.HttpResult = createHTTPResult();
3
+ exports.HttpResultUtils = void 0;
4
+ function Accepted() {
5
+ return {
6
+ status: 202,
7
+ };
8
+ }
9
+ function BadRequest(error) {
10
+ return {
11
+ status: 400,
12
+ jsonBody: JSON.stringify(error)
13
+ };
14
+ }
15
+ exports.HttpResultUtils = { Accepted, BadRequest };
@@ -26,4 +26,9 @@ export declare function toResult<T>(data: T): Result<T>;
26
26
  export declare function errorToErrorResult(error: Error): ErrorResult;
27
27
  export type ErrorName = "UnhandledError" | "Duplicate" | "NotFound" | "ApiError" | "ValidationError";
28
28
  export declare function toErrorResult(name: ErrorName, message: string, details?: Record<string, unknown>, code?: string, statusCode?: number): ErrorResult;
29
- export {};
29
+ declare const ResultUtils: {
30
+ toResult: typeof toResult;
31
+ errorToErrorResult: typeof errorToErrorResult;
32
+ toErrorResult: typeof toErrorResult;
33
+ };
34
+ export { ResultUtils };
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  // ResultUtils type for consistent responses
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.ResultUtils = void 0;
4
5
  exports.toResult = toResult;
5
6
  exports.errorToErrorResult = errorToErrorResult;
6
7
  exports.toErrorResult = toErrorResult;
@@ -24,6 +25,13 @@ function toErrorResult(name, message, details, code, statusCode) {
24
25
  code: code,
25
26
  details: details,
26
27
  statusCode: statusCode,
27
- timestamp: (0, dateUtils_1.formatDateTime)(new Date())
28
+ timestamp: dateUtils_1.DateUtils.formatDateTime(new Date())
28
29
  } };
29
30
  }
31
+ // Export everything as a single constant object
32
+ const ResultUtils = {
33
+ toResult,
34
+ errorToErrorResult,
35
+ toErrorResult,
36
+ };
37
+ exports.ResultUtils = ResultUtils;
@@ -1,4 +1,23 @@
1
+ import { z } from "zod";
2
+ export declare const numberIdSchema: z.ZodObject<{
3
+ id: z.ZodEffects<z.ZodNumber, number, unknown>;
4
+ }, "strip", z.ZodTypeAny, {
5
+ id: number;
6
+ }, {
7
+ id?: unknown;
8
+ }>;
1
9
  export declare function formatZodErrorsToString(errors: {
2
10
  path: (string | number)[];
3
11
  message: string;
4
12
  }[]): string;
13
+ declare const ValidationUtils: {
14
+ numberIdSchema: z.ZodObject<{
15
+ id: z.ZodEffects<z.ZodNumber, number, unknown>;
16
+ }, "strip", z.ZodTypeAny, {
17
+ id: number;
18
+ }, {
19
+ id?: unknown;
20
+ }>;
21
+ formatZodErrorsToString: typeof formatZodErrorsToString;
22
+ };
23
+ export { ValidationUtils };
@@ -1,8 +1,26 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ValidationUtils = exports.numberIdSchema = void 0;
3
4
  exports.formatZodErrorsToString = formatZodErrorsToString;
5
+ const zod_1 = require("zod");
6
+ exports.numberIdSchema = zod_1.z.object({
7
+ id: zod_1.z.preprocess((val) => {
8
+ // Convert strings and numbers to a number
9
+ if (typeof val === 'string' || typeof val === 'number') {
10
+ return Number(val);
11
+ }
12
+ throw new Error("Unsupported type for id"); // Explicitly throw for unsupported types
13
+ }, zod_1.z.number().positive({
14
+ message: 'must be a positive number',
15
+ })),
16
+ });
4
17
  function formatZodErrorsToString(errors) {
5
18
  return errors
6
19
  .map((err) => `${err.path.join(".")}: ${err.message}`)
7
20
  .join("\n");
8
21
  }
22
+ const ValidationUtils = {
23
+ numberIdSchema: exports.numberIdSchema,
24
+ formatZodErrorsToString,
25
+ };
26
+ exports.ValidationUtils = ValidationUtils;
@@ -1,11 +0,0 @@
1
- import { z } from "zod";
2
- export declare const idSchema: z.ZodObject<{
3
- id: z.ZodEffects<z.ZodNumber, number, unknown>;
4
- }, "strip", z.ZodTypeAny, {
5
- id: number;
6
- }, {
7
- id?: unknown;
8
- }>;
9
- export interface IdPayload {
10
- id: number;
11
- }
@@ -1,15 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.idSchema = void 0;
4
- const zod_1 = require("zod");
5
- exports.idSchema = zod_1.z.object({
6
- id: zod_1.z.preprocess((val) => {
7
- // Convert strings and numbers to a number
8
- if (typeof val === 'string' || typeof val === 'number') {
9
- return Number(val);
10
- }
11
- throw new Error("Unsupported type for id"); // Explicitly throw for unsupported types
12
- }, zod_1.z.number().positive({
13
- message: 'must be a positive number',
14
- })),
15
- });