@rvoh/dream
    Preparing search index...

    Class ObjectSerializerBuilder<MaybeNullDataType, PassthroughDataType, DataType>

    Type Parameters

    Index

    Constructors

    Properties

    attributes: (
        | InternalAnyTypedSerializerAttribute
        | InternalAnyTypedSerializerDelegatedAttribute
        | InternalAnyTypedSerializerCustomAttribute
        | InternalAnyTypedSerializerRendersOne<DataType, keyof DataType & string>
        | InternalAnyTypedSerializerRendersMany<DataType, keyof DataType & string>
    )[] = []
    passthroughData: PassthroughDataType = ...

    Methods

    • Includes an attribute from the data object in the serialized output.

      For ObjectSerializer, the openapi option is always required since type inference is not available for plain objects or ViewModels.

      Type Parameters

      • AttributeName extends string

      Parameters

      • name: AttributeName

        The attribute name from the data object

      • options: NonAutomaticSerializerAttributeOptionsWithPossibleDecimalRenderOption

        Configuration options:

        • openapi - (required) OpenAPI schema definition for the attribute
        • as - Rename the attribute key in the serialized output and OpenAPI shape
        • default - Value to use when the attribute is undefined
        • precision - Round decimal values to the specified number of decimal places (0–9) during rendering; does not affect the OpenAPI shape
        • required - Set to false to mark the attribute as optional in the OpenAPI schema; when omitted, attributes are required by default, meaning undefined values will serialize as null

      Returns ObjectSerializerBuilder<MaybeNullDataType, PassthroughDataType, DataType>

      The serializer builder for method chaining

      // Required OpenAPI schema
      .attribute('email', {
      openapi: { type: 'string', format: 'email' }
      })

      // With default value
      .attribute('status', {
      openapi: { type: 'string' },
      default: 'active'
      })

      // Rename output key
      .attribute('email', {
      openapi: { type: 'string' },
      as: 'userEmail'
      })

      // Round decimal to 2 places
      .attribute('price', {
      openapi: 'decimal',
      precision: 2
      })

      // Mark as optional in OpenAPI (omitted from response when undefined)
      .attribute('nickname', {
      openapi: 'string',
      required: false
      })
    • Includes a computed value in the serialized output.

      Executes a callback function to generate a custom attribute value. The openapi option is always required since the return type cannot be inferred.

      The callback's return value renders as is, so any fallback belongs in the callback.

      Parameters

      • name: string

        The attribute name for the computed value

      • fn: () => unknown

        Callback function that returns the computed value

      • options: CustomAttributeOptions

        Configuration options:

        • openapi - (required) OpenAPI schema definition for the computed value
        • flatten - When true, spreads the returned object's properties directly into the parent serialized output instead of nesting them under name. The openapi option then describes the whole returned object, not each property, because Psychic adds it to the parent's schema as an allOf branch: either an object schema with full property bodies (type: 'object', properties, and required listing the keys that are always present), or { $serializer: SomeSerializer } when the callback returns what that serializer renders. A serializer ref with many: true does not type-check here, since a list has no properties to spread. A null return, a serializer built over null or undefined data, or an undefined return without required: false renders as null each key the openapi requires: a key an object shape lists in its required array, a key a $serializer or $serializable ref's serializer declares without required: false, and each such key of an allOf, anyOf or oneOf member. Its optional keys stay absent, and an undefined return with required: false adds no keys. A returned plain object also renders as null each key its shape requires that it leaves out, and its optional keys it leaves out stay absent. When the openapi is an anyOf or oneOf, or a $serializable ref to an STI base, a present value also renders as null each key another variant requires that the rendered one does not declare, so a client sees the same keys whichever variant is rendered. Every key it adds follows the render's casing like the parent's own keys: a returned plain object's top-level keys and the openapi's properties keys are cased (so casing: 'snake' renders phoneNumber as phone_number, present or null), while nested values render as returned. Attributes render in declaration order, so a key the returned object shares with another attribute takes the value of whichever is declared later; under the allOf, that value must match both schemas
        • required - Set to false to mark the attribute as optional in the OpenAPI schema; when omitted, attributes are required by default

      Returns ObjectSerializerBuilder<MaybeNullDataType, PassthroughDataType, DataType>

      The serializer builder for method chaining

      // Simple computed value
      .customAttribute('fullName', () =>
      `${user.firstName} ${user.lastName}`,
      { openapi: { type: 'string' } }
      )

      // Flattened object properties: `openapi` describes the whole returned object
      .customAttribute('coordinates', () => ({ lat: 40.7, lng: -74.0 }), {
      flatten: true,
      openapi: {
      type: 'object',
      required: ['lat', 'lng'],
      properties: {
      lat: { type: 'number' },
      lng: { type: 'number' }
      }
      }
      })
    • Includes an attribute from a nested object in the serialized output.

      Accesses targetName.name on the data object. The openapi option is always required. When the target object or the delegated attribute is null/undefined, the resolution order is:

      1. default if provided → renders the default value
      2. required: false → omits the key entirely from the rendered output
      3. otherwise → renders null

      optional and required are not aliases — they encode different things and can be used together:

      • optional: true is an OpenAPI-only marker (no runtime effect). It declares that the rendered value may be null. Use this when you want the key to always be present but the value to be nullable in the schema.
      • required: false affects both runtime and OpenAPI. At runtime, when the resolved value is undefined, the key is omitted from the rendered output. In OpenAPI, the field is marked as not required.

      Type Parameters

      Parameters

      • targetName: TargetName

        The property name containing the target object

      • name: AttributeName

        The attribute name within the target object

      • options: NonAutomaticSerializerAttributeOptions & { precision?: RoundingPrecision } & {
            optional?: boolean;
        }

        Configuration options:

        • openapi - (required) OpenAPI schema definition for the attribute
        • as - Rename the attribute key in the serialized output and OpenAPI shape (e.g., delegating 'profile', 'avatarUrl' with as: 'avatar' outputs the value under avatar)
        • default - Value to use when the target object or its attribute is null/undefined
        • optional - Set to true to mark the value as nullable in the OpenAPI schema: Psychic adds null to the rendered schema (e.g., type: 'string' becomes type: ['string', 'null'], and a $ref becomes anyOf: [{ $ref }, { type: 'null' }]). OpenAPI-only — the key is still rendered (as null)
        • precision - Round decimal values to the specified number of decimal places (0–9) during rendering; does not affect the OpenAPI shape
        • required - Set to false to omit the key from the rendered output when the resolved value is undefined, and to mark the field as not required in the OpenAPI schema

      Returns ObjectSerializerBuilder<MaybeNullDataType, PassthroughDataType, DataType>

      The serializer builder for method chaining

      // Delegate to user.email
      .delegatedAttribute('user', 'email', {
      openapi: { type: 'string', format: 'email' }
      })

      // With default value for null target or attribute
      .delegatedAttribute('profile', 'displayName', {
      openapi: { type: 'string' },
      default: 'Anonymous User'
      })

      // Rename the output key
      .delegatedAttribute('profile', 'avatarUrl', {
      openapi: 'string',
      as: 'avatar'
      })
    • Executes the serializer and returns the serialized output.

      Processes all defined attributes, custom attributes, delegated attributes, and associations to produce the final serialized object.

      Parameters

      • passthrough: any = {}

        Additional data to pass through to nested serializers (e.g., locale, current user context)

      • opts: SerializerRendererOpts = {}

        Rendering options for customizing the serialization process

      Returns Record<string, any> | null

      The serialized object, suitable for JSON responses

      const result = UserViewModelSerializer(userVm).render()
      // Returns: { id: '123', email: 'user@example.com', ... }

      // With passthrough data for nested serializers
      const result = UserViewModelSerializer(userVm).render({ currentUserId: '456' })
    • Includes a single associated object in the serialized output.

      For ObjectSerializer, explicit serializer configuration is always required since association schemas cannot be inferred from plain objects.

      Type Parameters

      Parameters

      • name: AttributeName

        The association property name

      • options: { as?: string; flatten?: boolean; optional?: boolean } & SerializerOptions

        Configuration options:

        • as - Rename the association key in the serialized output
        • flatten - When true, spreads the rendered association's attributes directly into the parent serialized output instead of nesting them under name. Attributes render in declaration order, so when the parent and the association share a key (e.g., id), whichever is declared later wins: the association's value replaces an attribute declared before the rendersOne, and an attribute declared after it replaces the association's. When the association is null, each key its serializer requires renders as null: an attribute, delegatedAttribute or customAttribute declared without required: false, and every non-flattened rendersOne and rendersMany (for a polymorphic BelongsTo, each key the serializer of any of its target classes requires, and for an association to an STI base, each key the serializer of any of its STI children requires), in the same order (so an id declared before the rendersOne becomes null), while a key declared with required: false stays absent. A flattened customAttribute in that serializer adds the keys its openapi requires: a key an object shape lists in its required array, a key a $serializer or $serializable ref's serializer declares without required: false, and each such key of an allOf, anyOf or oneOf member; a ref with many: true adds none, and a flattened customAttribute declared with required: false adds none. Nothing in that serializer is rendered, so its custom attribute callbacks do not run. When the association to an STI base or polymorphic BelongsTo is present, each key another STI child's or target's serializer requires that the held one's serializer does not declare also renders as null, so a client sees the same keys whichever is held. Psychic adds the association's OpenAPI schema to the parent's as an allOf branch, so a shared key's value must match both schemas, whichever declaration wins
        • optional - When true, allows the association to be null/missing without causing an OpenapiResponseValidationFailure during Psychic controller unit specs. By default, rendersOne expects the association to be present (mirroring the optional option on @deco.BelongsTo). Set this to true when the association is genuinely nullable

        For Dream associations:

        • dreamClass - The Dream model class, enabling serializer inference; when specified, serializerKey may also be provided to select a specific registered serializer
        • serializer - Provide an explicit serializer function

        For ViewModel associations:

        • viewModelClass + optional serializerKey
        • serializer

        For non-Dream/non-ViewModel associations:

        • serializer is required
        • Optionalas?: string

          Rename the association key in the serialized output.

        • Optionalflatten?: boolean

          If true, the rendered association's attributes are merged directly into the parent object instead of being nested under the association key. A key the parent shares with the association takes the value of whichever is declared later, and when the association is null, each key its serializer requires renders as null. See the flatten option of rendersOne.

        • Optionaloptional?: boolean

          If true, the association is treated as nullable in the OpenAPI spec, allowing null when the association doesn't resolve. Set this for associations that may not exist.

      Returns ObjectSerializerBuilder<MaybeNullDataType, PassthroughDataType, DataType>

      The serializer builder for method chaining

      // With explicit serializer function
      .rendersOne('owner', { serializer: CustomOwnerSerializer })

      // With Dream class reference and serializer key
      .rendersOne('creator', {
      dreamClass: User,
      serializerKey: 'summary'
      })

      // Allow null association
      .rendersOne('approver', { serializer: UserSerializer, optional: true })

      // Flatten into parent object
      .rendersOne('profile', { serializer: ProfileSerializer, flatten: true })