{"id":21197663,"url":"https://github.com/ynixt/typescript-flat-serializer","last_synced_at":"2025-07-10T05:31:56.113Z","repository":{"id":172237153,"uuid":"648866078","full_name":"ynixt/typescript-flat-serializer","owner":"ynixt","description":"A typescript library to serialize/deserialize classes to/from string in a flat format. Supports inheritance, circular reference and more","archived":false,"fork":false,"pushed_at":"2024-03-21T02:12:22.000Z","size":229,"stargazers_count":3,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-11-13T11:57:32.996Z","etag":null,"topics":["flat","serialization","serializer","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ynixt.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2023-06-03T03:21:15.000Z","updated_at":"2023-10-11T01:12:04.000Z","dependencies_parsed_at":null,"dependency_job_id":"e27aa7d0-4833-4fe1-9251-aad3e1a13f37","html_url":"https://github.com/ynixt/typescript-flat-serializer","commit_stats":null,"previous_names":["ynixt/typescript-flat-serializer"],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ynixt%2Ftypescript-flat-serializer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ynixt%2Ftypescript-flat-serializer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ynixt%2Ftypescript-flat-serializer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ynixt%2Ftypescript-flat-serializer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ynixt","download_url":"https://codeload.github.com/ynixt/typescript-flat-serializer/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225622967,"owners_count":17498167,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["flat","serialization","serializer","typescript"],"created_at":"2024-11-20T19:45:53.753Z","updated_at":"2024-11-20T19:45:54.484Z","avatar_url":"https://github.com/ynixt.png","language":"TypeScript","readme":"# typescript-flat-serializer\n\n![Build status](https://github.com/ynixt/typescript-flat-serializer/workflows/Build/badge.svg)\n[![Coverage Status](https://coveralls.io/repos/github/ynixt/typescript-flat-serializer/badge.svg?branch=master)](https://coveralls.io/github/ynixt/typescript-flat-serializer?branch=master)\n[![Known Vulnerabilities](https://snyk.io/test/github/ynixt/typescript-flat-serializer/badge.svg?targetFile=package.json)](https://snyk.io/test/github/ynixt/typescript-flat-serializer?targetFile=package.json)\n![npm bundle size](https://img.shields.io/bundlephobia/minzip/typescript-flat-serializer)\n![GitHub](https://img.shields.io/github/license/ynixt/typescript-flat-serializer)\n![npm](https://img.shields.io/npm/v/typescript-flat-serializer)\n\nA typescript library to serialize/deserialize classes to/from string in a flat format. Supports inheritance, circular reference and more\n\n## Summary\n\n1. [Why](#why)\n2. [Installation](#installation)\n3. [Usage](#usage)\n4. [API](#API)\n5. [Important notes](#important-notes)\n6. [Inspired by](#inspired-by)\n\n## Why\n\nWhen I was developing a electron app I needed a serializer that fill some requirements to use with\n[IPC](https://www.electronjs.org/docs/latest/tutorial/ipc):\n\n- After serialize I wanted that the object keep the methods (right prototype)\n- I needed inheritance\n- Supports circular reference is always good\n\n## Installation\n\n`npm install typescript-flat-serializer --save`\n\n## Usage\n\n### With decorators\n\n#### Preparation\n\nIf you want to use our decorators you also need to set **experimentalDecorators** and **emitDecoratorMetadata**\nto true into the tsconfig.json file.\n\nFor example:\n\n```json\n{\n  \"compilerOptions\": {\n    ...\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    ...\n  }\n}\n```\n\n#### Usage\n\nFirst let's create some models\n\n```typescript\nimport { TSFlatCollection, TSFlatObject } from \"typescript-flat-serializer\";\n\n@TSFlatObject()\nexport abstract class Animal {\n  protected constructor(public name: string) {\n  }\n}\n\n// This decorator NEEDS to be placed on every class that you want to serialize. \n// Without this decorator the behavior will be like stringify/parse from JSON.\n@TSFlatObject()\nexport class Dog extends Animal {\n  // This decorator will take care of serialize/deserialize our collection\n  @TSFlatCollection({collectionType: \"set\"})\n  favoriteFoods: Set\u003cFood\u003e;\n\n  constructor(name: string, public beautiful: boolean, favoriteFoods: Set\u003cFood\u003e) {\n    super(name);\n    this.favoriteFoods = favoriteFoods;\n  }\n}\n\n@TSFlatObject()\nexport class Food extends Animal {\n  constructor(name: string) {\n    super(name);\n  }\n}\n```\n\nNow we only need to serialize/deserialize the animal.\n\n```typescript\nimport { parse, stringify } from \"typescript-flat-serializer\";\n\n\nconst foods = new Set([new Food('all')])\nconst animal: Animal = new Dog('Luffy', true, foods);\n\n// Let's go serialize our animal\nconst str = stringify(animal)\n// value of str: [{\"name\":\"Luffy\",\"beautiful\":true,\"favoriteFoods\":\"#_1_#\",\"__class__\":\"Dog\"},[\"#_2_#\"],{\"name\":\"all\",\"__class__\":\"Food\"}]\n\n// And now we can deserialize the animal\nconst parsedAnimal = parse\u003cAnimal\u003e(str);\n```\n\nYou can find another examples of utilisation on [tests](https://github.com/ynixt/typescript-flat-serializer/tree/master/test).\n\n### Without decorators\n\nFirst let's create some models\n\n```typescript\nimport { registerTSFlat } from \"typescript-flat-serializer\";\n\nexport abstract class Animal {\n  protected constructor(public name: string) {\n    registerTSFlat(\n      {\n        target: Animal,\n      }\n    );\n  }\n}\n\nexport class Dog extends Animal {\n  favoriteFoods: Set\u003cFood\u003e;\n\n  constructor(name: string, public beautiful: boolean, favoriteFoods: Set\u003cFood\u003e) {\n    super(name);\n    registerTSFlat(\n      {\n        target: Dog,\n      },\n      { collectionName: 'favoriteFoods', options: {collectionType: 'set'} }\n    )\n    this.favoriteFoods = favoriteFoods;\n  }\n}\n\nexport class Food extends Animal {\n  constructor(name: string) {\n    super(name);\n    registerTSFlat(\n      {\n        target: Food,\n      },\n    )\n  }\n}\n```\n\nNow we only need to serialize/deserialize the animal.\n\n```typescript\nimport {parse, stringify} from \"typescript-flat-serializer\";\n\n\nconst foods = new Set([new Food('all')])\nconst animal: Animal = new Dog('Luffy', true, foods);\n\n// Let's go serialize our animal\nconst str = stringify(animal)\n// value of str: [{\"name\":\"Luffy\",\"beautiful\":true,\"favoriteFoods\":\"#_1_#\",\"__class__\":\"Dog\"},[\"#_2_#\"],{\"name\":\"all\",\"__class__\":\"Food\"}]\n\n// And now we can deserialize the animal\nconst parsedAnimal = parse\u003cAnimal\u003e(str);\n```\n\n## API\n\n### Decorators\n\n#### **@TSFlatObject**\n\nUsed to make a class serializable.\n\n##### **Example**\n\n```typescript\n@TSFlatObject()\nexport class Dog {\n}\n```\n\n#### **@TSFlatCollection**\n\nUsed do make a Array|Set|Map|Dictionary\n\n##### **Example**\n\n```typescript\n@TSFlatObject()\nexport class Dog {\n  @TSFlatCollection({collectionType: \"map\"})\n  placesVisited: Map\u003cstring, boolean\u003e\n}\n```\n\n##### **Parameters**\n\n**collectionType**\nType: [`CollectionTypeString`](#collectionTypeString)  \nOptional: `false`  \nDescription: The way to specify the type of collection\n\n#### **@TSFlatProperty**\n\nUsed modify the serialization/deserialization of a property.\n\n##### **Example**\n\n```typescript\n@TSFlatObject()\nexport class Dog {\n  @TSFlatCollection({collectionType: \"map\"})\n  @TSFlatProperty({\n    beforeStringify: (m) =\u003e {\n      m.set('Brazil', true);\n    }\n  })\n  placesVisited: Map\u003cstring, boolean\u003e\n}\n```\n\n##### **Parameters**\n\n**options**\nType: [`TSFlatPropertyOptions`](#tSFlatPropertyOptions)  \nOptional: `true`  \nDescription: The option to customize the serialization/deserialization of the target property.\n\n### Methods\n\n#### **registerTSFlat**\n\nUsed do register an object and its items.\n\n```\nregisterTSFlat\u003cT\u003e(objectRegistration: FlatObjectRegistration\u003cT\u003e, ...items: FlatItem\u003cT\u003e[])\n```\n\n##### **Parameters**\n\n**objectRegistration**\n\nType: `FlatObjectRegistration\u003cT\u003e`  \nOptional: `false`  \nDescription: Information about the class that we want to make serializable.\n\nType: `FlatItem\u003cT\u003e[]`  \nOptional: `true`  \nDescription: Items that this class have that we want to make serializable.\n\n---\n\n#### **stringify**\n\nUsed to serialize a object.\n\n```\nstringify(obj: any, options?: StringifyOptions): string\n```\n\n##### **Parameters**\n\n**obj**\n\nType: `any`  \nOptional: `false`  \nDescription: The object that will be serialized\n\n**options**\n\nType: [`StringifyOptions`](#stringifyOptions)  \nOptional: `true`  \nDescription: Custom options to the serialization\n\n##### **Return**\n\n`string`\n\n---\n\n#### **parse**\n\nUsed to deserialize a string into a object.\n\n```\nparse\u003cT\u003e(str: string): T\n```\n\n##### **Return**\n\n`T`\n\n### Definitions\n\n#### **Types**\n\n\n##### **FlatObjectRegistration**\n\n```typescript\nexport type FlatObjectRegistration\u003cT\u003e = {\n  target: Type\u003cT\u003e,\n  options?: TSFlatObjectProperties\n}\n```\n\n##### **FlatItem\\\u003cT\u003e**\n\n```typescript\nexport type FlatItem\u003cT\u003e = FlatPropertyRegistration\u003cT\u003e | FlatCollectionRegistration\u003cT\u003e;\n```\n\n##### **FlatPropertyRegistration\\\u003cT\u003e**\n\n```typescript\nexport type FlatPropertyRegistration\u003cT\u003e = {\n  propertyName: (keyof T), options?: TSFlatPropertyOptions,\n}\n```\n\n##### **FlatCollectionRegistration\\\u003cT\u003e**\n\n```typescript\nexport type FlatCollectionRegistration\u003cT\u003e = {\n  collectionName: (keyof T), options: TSFlatCollectionOptions\n}\n```\n\n##### **CollectionTypeString**\n\n```typescript\nexport type CollectionTypeString = 'array' | 'dictionary' | 'map' | 'set';\n```\n\n##### **TSFlatPropertyOptions**\n\n```typescript\nexport type PropertyTransformer = (property: any) =\u003e any;\n\nexport interface TSFlatPropertyMetadata {\n    beforeStringify?: PropertyTransformer;\n    afterParse?: PropertyTransformer;\n}\n\nexport interface TSFlatPropertyOptions extends TSFlatPropertyMetadata {\n}\n```\n\n#### **stringifyOptions**\n\n```typescript\nexport type StringifyOptions = {\n  rFDCOptions?: RFDCOptions\n}\n\nexport type CustomWayOfCloningObjectMap = Map\u003cType\u003cany\u003e, (obj: any) =\u003e any\u003e;\n\nexport type RFDCOptions = {\n  customWayOfCloningObject?: CustomWayOfCloningObjectMap\n}\n```\n\n## Important notes\n\n### Cloning\n\nThis library before the serialization makes a clone of the object. By default the cloning supports the types:\n\n- Object\n- Array\n- Number\n- String\n- null\n- Date\n- undefined\n- Buffer\n- TypedArray\n- Map\n- Set\n- Function\n- AsyncFunction\n- GeneratorFunction\n- arguments\n\nTo support other type, like DateTime of [Luxon](https://github.com/moment/luxon/), you should do something like that:\n\n```typescript\nconst customWayOfCloningObject: CustomWayOfCloningObjectMap = new Map();\nconst rFDCOptions: RFDCOptions = {\n  customWayOfCloningObject\n}\n\ncustomWayOfCloningObject.set(DateTime, (obj) =\u003e DateTime.fromMillis(obj.toMillis()));\n\nconst str = stringify(obj, {rFDCOptions});\n```\n\n## Inspired by\n\n- [WebReflection/flatted](https://github.com/WebReflection/flatted)\n- [GillianPerard/typescript-json-serializer](https://github.com/GillianPerard/typescript-json-serializer)\n- [davidmarkclements/rfdc](https://github.com/davidmarkclements/rfdc)\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fynixt%2Ftypescript-flat-serializer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fynixt%2Ftypescript-flat-serializer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fynixt%2Ftypescript-flat-serializer/lists"}