From b96b71f990e191bf86c3bd5c46df62d3d598adfc Mon Sep 17 00:00:00 2001 From: Gabe Rodriguez Date: Wed, 20 Mar 2024 17:27:35 +0100 Subject: [PATCH] Validate zod only in dev --- packages/types/src/validation.test.ts | 15 +-------------- packages/types/src/validation.ts | 18 +++++------------- 2 files changed, 6 insertions(+), 27 deletions(-) diff --git a/packages/types/src/validation.test.ts b/packages/types/src/validation.test.ts index 95a53ac583..e95b952c4d 100644 --- a/packages/types/src/validation.test.ts +++ b/packages/types/src/validation.test.ts @@ -1,18 +1,9 @@ -import { afterEach, beforeEach, describe, expect, it, Mock, vi } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { z } from 'zod'; import { isType, validateSchema } from './validation'; describe('validation', () => { describe('validateSchema()', () => { - let mockLogger: Mock; - - beforeEach(() => { - mockLogger = vi.fn(); - vi.stubGlobal('console', { - error: mockLogger, - }); - }); - afterEach(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals(); @@ -49,7 +40,6 @@ describe('validation', () => { expect(() => { validateSchema(z.string(), 123); }).not.toThrow(); - expect(mockLogger).toHaveBeenCalledOnce(); }); it('Does not throw in chrome ext prod', () => { @@ -69,7 +59,6 @@ describe('validation', () => { expect(() => { validateSchema(z.string(), 123); }).not.toThrow(); - expect(mockLogger).toHaveBeenCalledOnce(); }); it('Does not throw in browser env', () => { @@ -82,7 +71,6 @@ describe('validation', () => { expect(() => { validateSchema(z.string(), 123); }).not.toThrow(); - expect(mockLogger).toHaveBeenCalledOnce(); }); it('Does not throw in unknown env', () => { @@ -95,7 +83,6 @@ describe('validation', () => { expect(() => { validateSchema(z.string(), 123); }).not.toThrow(); - expect(mockLogger).toHaveBeenCalledOnce(); }); }); diff --git a/packages/types/src/validation.ts b/packages/types/src/validation.ts index ff6e6c471c..73303e0127 100644 --- a/packages/types/src/validation.ts +++ b/packages/types/src/validation.ts @@ -1,21 +1,13 @@ import { z, ZodTypeAny } from 'zod'; import { isDevEnv } from './environment'; -// In production, we do not want to throw validation errors, but log them. -// Given the extension update cycle, we want to opt for grace degradation. -// In our CI/CD, we'll throw validation errors so they can be fixed at build time. +// Given performance critical nature of some features (like syncing), +// we only validate in dev mode in attempts to catch any schema variance export const validateSchema = (schema: z.ZodSchema, data: unknown): T => { - const result = schema.safeParse(data); - - if (result.success) { - return result.data; + if (isDevEnv()) { + return schema.parse(data); } else { - if (isDevEnv()) { - throw result.error; - } else { - console.error(result.error); - return data as T; - } + return data as T; } };