ts-serializable 4.2.2 → 4.3.2

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.
@@ -1,14 +1,30 @@
1
1
  import type { AcceptedTypes } from "../models/AcceptedType.js";
2
2
  import { SerializationSettings } from "../models/SerializationSettings.js";
3
3
  /**
4
- * Class that helps you deserialize objects to classes.
4
+ * Base class that provides serialization and deserialization functionality for converting
5
+ * objects to and from JSON format. This class uses decorators to define how properties
6
+ * should be serialized and deserialized.
5
7
  *
6
8
  * @export
7
9
  * @class Serializable
10
+ * @example
11
+ * ```typescript
12
+ * class User extends Serializable {
13
+ * @JsonProperty()
14
+ * name: string;
15
+ *
16
+ * @JsonProperty()
17
+ * age: number;
18
+ * }
19
+ *
20
+ * const user = User.fromJSON({ name: "John", age: 30 });
21
+ * const json = user.toJSON();
22
+ * ```
8
23
  */
9
24
  export declare class Serializable {
10
25
  /**
11
- * Global settings for serialization and deserialization.
26
+ * Global default settings for all serialization and deserialization operations.
27
+ * These settings can be overridden per operation by passing custom settings.
12
28
  *
13
29
  * @static
14
30
  * @type {SerializationSettings}
@@ -16,109 +32,174 @@ export declare class Serializable {
16
32
  */
17
33
  static defaultSettings: SerializationSettings;
18
34
  /**
19
- * Deserialize an object using a static method.
20
- *
21
- * Example:
22
- * const obj: MyObject = MyObject.fromJSON({...data});
35
+ * Creates a new instance of the class and deserializes JSON data into it.
36
+ * This is a convenient static method that combines instantiation and deserialization.
23
37
  *
24
38
  * @static
25
- * @param {object} json
26
- * @returns {object}
39
+ * @template T - The type of the Serializable class
40
+ * @param {object} json - The JSON object to deserialize
41
+ * @param {Partial<SerializationSettings>} [settings] - Optional settings to override default serialization behavior
42
+ * @returns {T} A new instance of the class with properties populated from the JSON
27
43
  * @memberof Serializable
44
+ * @example
45
+ * ```typescript
46
+ * const user = User.fromJSON({ name: "John", age: 30 });
47
+ * ```
28
48
  */
29
49
  static fromJSON<T extends Serializable>(this: new () => T, json: object, settings?: Partial<SerializationSettings>): T;
30
50
  /**
31
- * Deserialize an object from a string using a static method.
32
- *
33
- * Example:
34
- * const obj: MyObject = MyObject.fromString("{...data}");
51
+ * Creates a new instance of the class and deserializes JSON string data into it.
52
+ * Automatically parses the JSON string before deserialization.
35
53
  *
36
54
  * @static
37
- * @param {string} str
38
- * @returns {object}
55
+ * @template T - The type of the Serializable class
56
+ * @param {string} str - The JSON string to parse and deserialize
57
+ * @param {Partial<SerializationSettings>} [settings] - Optional settings to override default serialization behavior
58
+ * @returns {T} A new instance of the class with properties populated from the parsed JSON
39
59
  * @memberof Serializable
60
+ * @throws {SyntaxError} If the string is not valid JSON
61
+ * @example
62
+ * ```typescript
63
+ * const user = User.fromString('{"name":"John","age":30}');
64
+ * ```
40
65
  */
41
66
  static fromString<T extends Serializable>(this: new () => T, str: string, settings?: Partial<SerializationSettings>): T;
42
67
  /**
43
- * Fill properties of the current model with data from a string.
68
+ * Populates the current instance's properties with data from a JSON object.
69
+ * Uses metadata from decorators to determine how to deserialize each property.
44
70
  *
45
- * Example:
46
- * const obj: MyObject = new MyObject().fromString("{...data}");
47
- *
48
- * @param {string} str
49
- * @returns {this}
71
+ * @param {object} json - The JSON object containing data to populate the instance
72
+ * @param {Partial<SerializationSettings>} [settings] - Optional settings to override default serialization behavior
73
+ * @returns {this} The current instance for method chaining
50
74
  * @memberof Serializable
75
+ * @example
76
+ * ```typescript
77
+ * const user = new User();
78
+ * user.fromJSON({ name: "John", age: 30 });
79
+ * ```
51
80
  */
52
- fromString(str: string, settings?: Partial<SerializationSettings>): this;
81
+ fromJSON(json: object, settings?: Partial<SerializationSettings>): this;
53
82
  /**
54
- * Fill properties of the current model with data from JSON.
55
- *
56
- * Example:
57
- * const obj: MyObject = new MyObject().fromJSON({...data});
83
+ * Populates the current instance's properties with data from a JSON string.
84
+ * Automatically parses the JSON string before populating properties.
58
85
  *
59
- * @param {object} json
60
- * @returns {this}
86
+ * @param {string} str - The JSON string to parse and use for populating the instance
87
+ * @param {Partial<SerializationSettings>} [settings] - Optional settings to override default serialization behavior
88
+ * @returns {this} The current instance for method chaining
61
89
  * @memberof Serializable
90
+ * @throws {SyntaxError} If the string is not valid JSON
91
+ * @example
92
+ * ```typescript
93
+ * const user = new User();
94
+ * user.fromString('{"name":"John","age":30}');
95
+ * ```
62
96
  */
63
- fromJSON(json: object, settings?: Partial<SerializationSettings>): this;
97
+ fromString(str: string, settings?: Partial<SerializationSettings>): this;
64
98
  /**
65
- * Process serialization for the @jsonIgnore decorator.
99
+ * Serializes the current instance to a plain JavaScript object.
100
+ * Respects @JsonIgnore decorators to exclude specific properties from serialization.
101
+ * Applies naming strategies and @JsonName decorators for property name transformation.
66
102
  *
67
- * @returns {object}
103
+ * @returns {Record<string, unknown>} A plain object representation of the instance
68
104
  * @memberof Serializable
105
+ * @example
106
+ * ```typescript
107
+ * const user = new User();
108
+ * user.name = "John";
109
+ * user.age = 30;
110
+ * const json = user.toJSON(); // { name: "John", age: 30 }
111
+ * ```
69
112
  */
70
113
  toJSON(): Record<string, unknown>;
71
114
  /**
72
- * Serialize the class to FormData.
73
- *
74
- * Can be used to prepare an AJAX form with files.
75
- * Sending files via AJAX JSON is a heavy task because it requires converting files to base64 format.
76
- * The user interface can freeze for several seconds during this operation if the file is too large.
77
- * AJAX forms are a lightweight alternative.
78
- *
79
- * @param {string} formPrefix Prefix for form property names
80
- * @param {FormData} formData Can update an existing FormData
81
- * @returns {FormData}
115
+ * Serializes the current instance to FormData format, suitable for multipart/form-data requests.
116
+ * This is particularly useful for AJAX form submissions that include file uploads.
117
+ * Unlike JSON serialization with base64-encoded files, FormData provides better performance
118
+ * and avoids UI freezing when handling large files.
119
+ *
120
+ * @param {string} [formPrefix] - Optional prefix to prepend to all form field names
121
+ * @param {FormData} [formData] - Optional existing FormData instance to append to
122
+ * @returns {FormData} A FormData instance containing the serialized data
82
123
  * @memberof Serializable
124
+ * @example
125
+ * ```typescript
126
+ * const user = new User();
127
+ * user.name = "John";
128
+ * user.avatar = fileInput.files[0];
129
+ * const formData = user.toFormData();
130
+ * // Use with fetch: fetch('/api/users', { method: 'POST', body: formData });
131
+ * ```
83
132
  */
84
133
  toFormData(formPrefix?: string, formData?: FormData): FormData;
85
134
  /**
86
- * Process serialization for the @jsonIgnore decorator.
135
+ * Serializes the current instance to a JSON string.
136
+ * This is a convenience method that combines toJSON() with JSON.stringify().
87
137
  *
88
- * @returns {string}
138
+ * @returns {string} A JSON string representation of the instance
89
139
  * @memberof Serializable
140
+ * @example
141
+ * ```typescript
142
+ * const user = new User();
143
+ * user.name = "John";
144
+ * user.age = 30;
145
+ * const jsonString = user.toString(); // '{"name":"John","age":30}'
146
+ * ```
90
147
  */
91
148
  toString(): string;
92
149
  /**
93
- * Process exceptions for incorrect types.
94
- * By default, it just prints a warning in the console, but it can be overridden to throw exceptions or log to the backend.
95
- *
96
- * @protected
97
- * @param {string} prop
98
- * @param {string} message
99
- * @param {(unknown)} jsonValue
150
+ * Handles type mismatch errors during deserialization.
151
+ * By default, logs an error to the console. Can be overridden in subclasses to implement
152
+ * custom error handling such as throwing exceptions, logging to external services, or
153
+ * collecting validation errors.
154
+ *
155
+ * @public
156
+ * @param {string} prop - The name of the property that has a type mismatch
157
+ * @param {string} message - A description of the type error
158
+ * @param {unknown} jsonValue - The actual value that caused the type mismatch
100
159
  * @memberof Serializable
160
+ * @example
161
+ * ```typescript
162
+ * class User extends Serializable {
163
+ * onWrongType(prop: string, message: string, jsonValue: unknown): void {
164
+ * throw new Error(`Invalid ${prop}: ${message}`);
165
+ * }
166
+ * }
167
+ * ```
101
168
  */
102
- protected onWrongType(prop: string, message: string, jsonValue: unknown): void;
169
+ onWrongType(prop: string, message: string, jsonValue: unknown): void;
103
170
  /**
104
- * Deserialize one property.
105
- *
106
- * @private
107
- * @param {object} object
108
- * @param {string} prop
109
- * @param {AcceptedTypes[]} acceptedTypes
110
- * @param {(unknown)} jsonValue
111
- * @returns {(Object | null | void)}
171
+ * Deserializes a single property value based on its accepted types.
172
+ * This method is used internally during deserialization to convert JSON values
173
+ * to the appropriate TypeScript types defined by decorators.
174
+ *
175
+ * @public
176
+ * @param {string} prop - The name of the property being deserialized
177
+ * @param {AcceptedTypes[]} acceptedTypes - Array of allowed types for this property
178
+ * @param {unknown} jsonValue - The JSON value to deserialize
179
+ * @param {Partial<SerializationSettings>} [settings] - Optional settings to override default behavior
180
+ * @returns {unknown} The deserialized value matching one of the accepted types
112
181
  * @memberof Serializable
113
182
  */
114
- protected deserializeProperty(prop: string, acceptedTypes: AcceptedTypes[], jsonValue: unknown, settings?: Partial<SerializationSettings>): unknown;
183
+ deserializeProperty(prop: string, acceptedTypes: AcceptedTypes[], jsonValue: unknown, settings?: Partial<SerializationSettings>): unknown;
115
184
  /**
116
- * Extract the correct name for a property.
117
- * Considers decorators for transforming the property name.
118
- *
119
- * @param {string} property Source name of the property
120
- * @param {Partial<SerializationSettings>} settings Serialization settings
121
- * @returns
185
+ * Determines the JSON property name for a given class property.
186
+ * Takes into account @JsonName decorators and naming strategies (camelCase, snake_case, etc.)
187
+ * defined in the serialization settings.
188
+ *
189
+ * @public
190
+ * @param {string} property - The source property name as defined in the class
191
+ * @param {Partial<SerializationSettings>} [settings] - Optional settings to override default naming behavior
192
+ * @returns {string} The transformed property name to use in JSON
193
+ * @memberof Serializable
194
+ * @example
195
+ * ```typescript
196
+ * // With @JsonName decorator
197
+ * class User extends Serializable {
198
+ * @JsonName("user_name")
199
+ * userName: string;
200
+ * }
201
+ * // user.getJsonPropertyName("userName") returns "user_name"
202
+ * ```
122
203
  */
123
- protected getJsonPropertyName(property: string, settings?: Partial<SerializationSettings>): string;
204
+ getJsonPropertyName(property: string, settings?: Partial<SerializationSettings>): string;
124
205
  }