Skip to content

Commit

Permalink
Validate zod only in dev (#802)
Browse files Browse the repository at this point in the history
  • Loading branch information
grod220 authored Mar 20, 2024
1 parent e889b9a commit a00639d
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 27 deletions.
15 changes: 1 addition & 14 deletions packages/types/src/validation.test.ts
Original file line number Diff line number Diff line change
@@ -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();
Expand Down Expand Up @@ -49,7 +40,6 @@ describe('validation', () => {
expect(() => {
validateSchema(z.string(), 123);
}).not.toThrow();
expect(mockLogger).toHaveBeenCalledOnce();
});

it('Does not throw in chrome ext prod', () => {
Expand All @@ -69,7 +59,6 @@ describe('validation', () => {
expect(() => {
validateSchema(z.string(), 123);
}).not.toThrow();
expect(mockLogger).toHaveBeenCalledOnce();
});

it('Does not throw in browser env', () => {
Expand All @@ -82,7 +71,6 @@ describe('validation', () => {
expect(() => {
validateSchema(z.string(), 123);
}).not.toThrow();
expect(mockLogger).toHaveBeenCalledOnce();
});

it('Does not throw in unknown env', () => {
Expand All @@ -95,7 +83,6 @@ describe('validation', () => {
expect(() => {
validateSchema(z.string(), 123);
}).not.toThrow();
expect(mockLogger).toHaveBeenCalledOnce();
});
});

Expand Down
18 changes: 5 additions & 13 deletions packages/types/src/validation.ts
Original file line number Diff line number Diff line change
@@ -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 = <T>(schema: z.ZodSchema<T>, 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;
}
};

Expand Down

0 comments on commit a00639d

Please sign in to comment.