Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.strict() mode to remove excess properties. Not throw an error? #74

Open
burtonator opened this issue Jan 21, 2025 · 1 comment
Open

Comments

@burtonator
Copy link

I have a situation where I need to write a Cat object via tRPC but the procedure only accepts a Pet.

(contrived example).

the Cat property has a "whiskers" param which Pet does not have so it throws an error when I'm trying to call tRPC.

This compiles just fine with Typescript but I get a runtime error when I try to write to the DB.

I think we should have a strict() version of wrap() where Zod will remove the excess properties.

This way it can write the Pet to the db without the whiskers param.

@burtonator
Copy link
Author

burtonator commented Jan 21, 2025

I think the following changes could work in validationAdapter:

import type {AdapterResolver} from './resolver';
import type {ValidationAdapter} from '@typeschema/core';
import {memoize} from '@typeschema/core';
import Ajv from "ajv";
import addFormats from 'ajv-formats'

const importValidationModule = memoize(async () => {
  const {TypeCompiler} = await import('@sinclair/typebox/compiler');
  return {TypeCompiler};
});

export const validationAdapter: ValidationAdapter<
  AdapterResolver
> = async schema => {
  const {TypeCompiler} = await importValidationModule();
  const checker = TypeCompiler.Compile(schema);

  const ajv = addFormats(new Ajv({
    removeAdditional: 'all',
    useDefaults: true,
  }), [
    'date-time',
    'time',
    'date',
    'email',
    'hostname',
    'ipv4',
    'ipv6',
    'uri',
    'uri-reference',
    'uuid',
    'uri-template',
    'json-pointer',
    'relative-json-pointer',
    'regex'
  ])

  const validate = ajv.compile(schema)

  return async data => {

    validate(data)

    if (checker.Check(data)) {
      return {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        data: data as any,
        success: true,
      };
    }

    return {
      issues: [...checker.Errors(data)].map(({message, path}) => ({
        message,
        path: [path],
      })),
      success: false,
    };
  };
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant