Skip to content

Support Runtime Type Validation for JSON Messages #27

@Matan-Yadaev-Forter

Description

@Matan-Yadaev-Forter

Currently, @platformatic/kafka only supports compile-time type assertions like jsonSerializer<Person>. However, runtime type validation is becoming a common practice in the TypeScript ecosystem.

It would be great if the library supported runtime validation out of the box, even though it's easy to extend manually.

Here's an example using Zod:

import { Consumer, stringDeserializer } from '@platformatic/kafka';
import { z } from 'zod';

const JsonStringSchema = z
    .string()
    .transform((str, ctx) => {
      try {
        return JSON.parse(str);
      } catch {
        ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Invalid JSON' });
        return z.NEVER;
      }
    });

const UserSchema = z.object({
  id: z.string(),
  name: z.string(),
  age: z.number(),
});

const userDeserializer = (data: Buffer) => {
  const jsonString = data.toString();

  const result = JsonStringSchema
    .pipe(UserSchema)
    .safeParse(jsonString);

  if (!result.success) {
    console.error('Validation failed:', result.error.issues);
    return;
  }

  return result.data;
};

const consumer = new Consumer({
  deserializers: {
    key: stringDeserializer,
    value: userDeserializer,
  },
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions