or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication.mdindex.mdoperations.mdpipeline.mdpolicies.mdserialization.mdservice-client.md
tile.json

serialization.mddocs/

Serialization Framework

Comprehensive mapper-based system for transforming data between user-friendly JavaScript objects and HTTP request/response payloads. The serialization framework handles complex data types, nested objects, arrays, and XML/JSON formats based on OpenAPI specifications.

Capabilities

Serializer Creation

Creates a serializer instance for data model mapping and transformation with support for both JSON and XML formats.

/**
 * Creates a serializer for data model mapping and transformation
 * @param modelMappers - Registry of model mappers by name
 * @param isXML - Whether this serializer handles XML format
 * @returns Serializer instance for data transformation
 */
function createSerializer(
  modelMappers?: { [key: string]: any }, 
  isXML?: boolean
): Serializer;

Serializer Interface

Core interface for serializing JavaScript objects to HTTP payloads and deserializing HTTP responses back to JavaScript objects.

/**
 * Interface for serializing/deserializing data between JavaScript objects and HTTP payloads
 */
interface Serializer {
  /**
   * Transform a JavaScript object to wire format for HTTP requests
   * @param mapper - Mapper defining the transformation rules
   * @param object - The object to serialize
   * @param objectName - Name for error reporting
   * @param options - Serialization options
   * @returns Serialized data ready for HTTP transmission
   */
  serialize(
    mapper: Mapper, 
    object: any, 
    objectName?: string, 
    options?: SerializerOptions
  ): any;

  /**
   * Transform wire format data to a JavaScript object
   * @param mapper - Mapper defining the transformation rules
   * @param responseBody - The response data to deserialize
   * @param objectName - Name for error reporting
   * @param options - Serialization options
   * @returns Deserialized JavaScript object
   */
  deserialize(
    mapper: Mapper, 
    responseBody: any, 
    objectName: string, 
    options?: SerializerOptions
  ): any;

  /**
   * Validate object constraints (deprecated)
   * @deprecated Constraint validation is being removed from client side
   */
  validateConstraints(mapper: Mapper, value: any, objectName: string): void;

  /** Registry of registered model mappers */
  readonly modelMappers: { [key: string]: any };

  /** Whether this serializer handles XML format */
  readonly isXML: boolean;
}

Mapper Type Names

Enumeration of known mapper types for serialization, providing constants for all supported data types.

/**
 * Known types of mappers for serialization
 */
const MapperTypeNames: {
  readonly Base64Url: "Base64Url";
  readonly Boolean: "Boolean";
  readonly ByteArray: "ByteArray";
  readonly Composite: "Composite";
  readonly Date: "Date";
  readonly DateTime: "DateTime";
  readonly DateTimeRfc1123: "DateTimeRfc1123";
  readonly Dictionary: "Dictionary";
  readonly Enum: "Enum";
  readonly Number: "Number";
  readonly Object: "Object";
  readonly Sequence: "Sequence";
  readonly String: "String";
  readonly Stream: "Stream";
  readonly TimeSpan: "TimeSpan";
  readonly UnixTime: "UnixTime";
};

Mapper System

Base Mapper

Foundation interface for all mappers, defining common properties for serialization metadata.

/**
 * Base definition for all mappers used in serialization/deserialization
 */
interface BaseMapper {
  /** XML element name for XML serialization */
  xmlName?: string;
  /** XML namespace for XML serialization */
  xmlNamespace?: string;
  /** XML namespace prefix */
  xmlNamespacePrefix?: string;
  /** Whether to serialize as XML attribute */
  xmlIsAttribute?: boolean;
  /** Whether property contains text content in XML */
  xmlIsMsText?: boolean;
  /** XML element name override */
  xmlElementName?: string;
  /** Whether XML element should be wrapped */
  xmlIsWrapped?: boolean;
  /** Whether property is read-only */
  readOnly?: boolean;
  /** Whether property has a constant value */
  isConstant?: boolean;
  /** Whether property is required */
  required?: boolean;
  /** Whether property can be null */
  nullable?: boolean;
  /** Name used in serialized form */
  serializedName?: string;
  /** Type information for serialization */
  type: MapperType;
  /** Default value if not provided */
  defaultValue?: any;
  /** Validation constraints */
  constraints?: MapperConstraints;
}

Specific Mapper Types

/**
 * Union type of all specific mapper types
 */
type Mapper = BaseMapper | CompositeMapper | SequenceMapper | DictionaryMapper | EnumMapper;

/**
 * Mapper for object/composite types
 */
interface CompositeMapper extends BaseMapper {
  type: CompositeMapperType;
  /** Parent type for inheritance */
  uberParent?: string;
  /** Discriminator for polymorphic types */
  polymorphicDiscriminator?: PolymorphicDiscriminator;
}

/**
 * Mapper for array/sequence types
 */
interface SequenceMapper extends BaseMapper {
  type: SequenceMapperType;
}

/**
 * Mapper for key-value pair/dictionary types
 */
interface DictionaryMapper extends BaseMapper {
  type: DictionaryMapperType;
}

/**
 * Mapper for enumeration types
 */
interface EnumMapper extends BaseMapper {
  type: EnumMapperType;
}

Mapper Type Descriptors

/**
 * Union of all mapper type descriptors
 */
type MapperType = SimpleMapperType | CompositeMapperType | SequenceMapperType | DictionaryMapperType | EnumMapperType;

/**
 * Type descriptor for primitive types
 */
interface SimpleMapperType {
  /** Type name (e.g., "String", "Number") */
  name: string;
}

/**
 * Type descriptor for composite/object types
 */
interface CompositeMapperType {
  name: "Composite";
  /** Property mappings for object fields */
  modelProperties?: { [propertyName: string]: Mapper };
  /** Mapper for additional properties */
  additionalProperties?: Mapper;
  /** Class name for instantiation */
  className?: string;
}

/**
 * Type descriptor for array/sequence types
 */
interface SequenceMapperType {
  name: "Sequence";
  /** Mapper for array elements */
  element: Mapper;
}

/**
 * Type descriptor for dictionary/map types
 */
interface DictionaryMapperType {
  name: "Dictionary";
  /** Mapper for dictionary values */
  value: Mapper;
}

/**
 * Type descriptor for enumeration types
 */
interface EnumMapperType {
  name: "Enum";
  /** Array of allowed enum values */
  allowedValues: any[];
}

Validation Constraints

/**
 * Validation constraints for mapper values
 */
interface MapperConstraints {
  /** Maximum value (inclusive) */
  InclusiveMaximum?: number;
  /** Maximum value (exclusive) */
  ExclusiveMaximum?: number;
  /** Minimum value (inclusive) */
  InclusiveMinimum?: number;
  /** Minimum value (exclusive) */
  ExclusiveMinimum?: number;
  /** Maximum string/array length */
  MaxLength?: number;
  /** Minimum string/array length */
  MinLength?: number;
  /** RegExp pattern for string validation */
  Pattern?: string;
  /** Maximum array items */
  MaxItems?: number;
  /** Minimum array items */
  MinItems?: number;
  /** Whether array items must be unique */
  UniqueItems?: boolean;
  /** Value must be multiple of this number */
  MultipleOf?: number;
}

Serialization Options

Serializer Options

Configuration options that control serialization behavior for both JSON and XML formats.

/**
 * Options to configure serialization/de-serialization behavior
 */
interface SerializerOptions {
  /** XML-specific options */
  xml: XmlOptions;
  /** Whether to ignore unmapped properties during deserialization */
  ignoreUnknownProperties?: boolean;
}

/**
 * XML parsing and building options
 */
interface XmlOptions {
  /** Name of root element when building XML */
  rootName?: string;
  /** Whether to include root element when parsing XML */
  includeRoot?: boolean;
  /** Key for accessing character content (defaults to XML_CHARKEY) */
  xmlCharKey?: string;
}

XML Constants

/** Default key used to access XML attributes during parsing/serialization */
const XML_ATTRKEY: string; // "$"

/** Default key used to access XML character content during parsing/serialization */
const XML_CHARKEY: string; // "_"

Usage Examples

Basic Serialization

import { createSerializer } from "@azure/core-client";

// Create a serializer
const serializer = createSerializer();

// Define a simple mapper
const userMapper = {
  type: { name: "Composite" },
  modelProperties: {
    name: {
      serializedName: "name",
      type: { name: "String" }
    },
    age: {
      serializedName: "age",
      type: { name: "Number" }
    }
  }
};

// Serialize an object
const user = { name: "Alice", age: 30 };
const serializedUser = serializer.serialize(userMapper, user, "User");
// Result: { "name": "Alice", "age": 30 }

// Deserialize back to object
const deserializedUser = serializer.deserialize(userMapper, serializedUser, "User");

Complex Object Serialization

import { createSerializer } from "@azure/core-client";

const serializer = createSerializer();

// Complex mapper with nested objects and arrays
const orderMapper = {
  type: { name: "Composite" },
  modelProperties: {
    id: {
      serializedName: "id",
      type: { name: "String" }
    },
    customer: {
      serializedName: "customer",
      type: {
        name: "Composite",
        modelProperties: {
          name: { serializedName: "name", type: { name: "String" } },
          email: { serializedName: "email", type: { name: "String" } }
        }
      }
    },
    items: {
      serializedName: "items",
      type: {
        name: "Sequence",
        element: {
          type: {
            name: "Composite",
            modelProperties: {
              productId: { serializedName: "product_id", type: { name: "String" } },
              quantity: { serializedName: "qty", type: { name: "Number" } }
            }
          }
        }
      }
    }
  }
};

const order = {
  id: "ORD-123",
  customer: {
    name: "John Doe",
    email: "john@example.com"
  },
  items: [
    { productId: "PROD-1", quantity: 2 },
    { productId: "PROD-2", quantity: 1 }
  ]
};

const serializedOrder = serializer.serialize(orderMapper, order, "Order");

XML Serialization

import { createSerializer, XML_ATTRKEY, XML_CHARKEY } from "@azure/core-client";

// Create XML serializer
const xmlSerializer = createSerializer({}, true);

// XML mapper with attributes
const bookMapper = {
  type: { name: "Composite" },
  xmlName: "book",
  modelProperties: {
    id: {
      serializedName: "id",
      xmlIsAttribute: true,
      type: { name: "String" }
    },
    title: {
      serializedName: "title",
      xmlName: "title",
      type: { name: "String" }
    },
    author: {
      serializedName: "author",
      xmlName: "author",
      type: { name: "String" }
    }
  }
};

const book = { id: "B123", title: "Azure Guide", author: "Jane Smith" };
const xmlResult = xmlSerializer.serialize(bookMapper, book, "Book", {
  xml: { rootName: "book" }
});
// Result: <book id="B123"><title>Azure Guide</title><author>Jane Smith</author></book>

Enum Serialization

import { createSerializer } from "@azure/core-client";

const serializer = createSerializer();

// Enum mapper
const statusMapper = {
  serializedName: "status",
  type: {
    name: "Enum",
    allowedValues: ["active", "inactive", "pending"]
  }
};

const status = "active";
const serializedStatus = serializer.serialize(statusMapper, status, "Status");
// Result: "active"

Date Serialization

import { createSerializer } from "@azure/core-client";

const serializer = createSerializer();

// Date mapper
const eventMapper = {
  type: { name: "Composite" },
  modelProperties: {
    createdAt: {
      serializedName: "created_at",
      type: { name: "DateTime" }
    },
    lastModified: {
      serializedName: "last_modified",
      type: { name: "DateTimeRfc1123" }
    }
  }
};

const event = {
  createdAt: new Date("2023-01-15T10:30:00Z"),
  lastModified: new Date("2023-01-16T14:22:00Z")
};

const serializedEvent = serializer.serialize(eventMapper, event, "Event");
// Result: { 
//   "created_at": "2023-01-15T10:30:00.000Z", 
//   "last_modified": "Sun, 16 Jan 2023 14:22:00 GMT" 
// }

Integration with Operation Specs

Serializers work seamlessly with OperationSpec to handle request/response transformation:

import { createSerializer, ServiceClient } from "@azure/core-client";
import type { OperationSpec } from "@azure/core-client";

const serializer = createSerializer();

const createUserSpec: OperationSpec = {
  httpMethod: "POST",
  path: "/users",
  serializer,
  requestBody: {
    parameterPath: "user",
    mapper: {
      type: { name: "Composite" },
      modelProperties: {
        name: { serializedName: "name", type: { name: "String" } },
        email: { serializedName: "email", type: { name: "String" } }
      }
    }
  },
  responses: {
    201: {
      bodyMapper: {
        type: { name: "Composite" },
        modelProperties: {
          id: { serializedName: "id", type: { name: "String" } },
          name: { serializedName: "name", type: { name: "String" } },
          email: { serializedName: "email", type: { name: "String" } }
        }
      }
    }
  }
};