question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Feature Request: Allow generating an object with a full set of defaults that may not validate

See original GitHub issue

I am looking to use zod as a way to validate user configuration files for a command line utility. It looks like a great fit compared to what we are doing now, but I am having trouble with one aspect.

The workflow we use is:

  • Allocate an initial set of defaults in a nested object (note: this isn’t fully filled in so won’t validate the schema)
  • Pass to a user provided configuration function (ex. app.config.js) that extends the configuration
  • Fill in final settings based upon combination of user and defaults
  • Validate final config with schema. (looking for extra properties, validation checks, etc)

My problem is that in this model I don’t see a way to use zod to create the initial defaults object. I know I could create it as a plain old javascript object separate from the schema, but I was hoping to take advantage of the .default() methods within the schema to have the schema be self describing without having a separate large defaults object.

So my hope was to make something like this work:

const ConfigSchema = z.object({
   /** The name to use. */
   name: z.string().default('blah'),

   /** Another nested part. */
   nested: z
      .object({
         value: z.number(),
         val2: z
            .string()
            .nullable()
            .refine((v) => v && v.length === 5, 'Must be length 5.'),
      })
      .default({
         value: 20,
         val2: null,
      }),
});

type ConfigType = z.infer<typeof ConfigSchema>;

describe('zod', () => {
   it('validates a good value', () => {});

   it('can provide defaults to override', () => {
      // We can build a set of default values that don't validate yet
      const default_results = ConfigSchema.safeParse({});  // <--- Need something here to just get defaults
      const cfg = default_results.data;

      expect(cfg.nested.val2).toEqual(null);

      // then: user modifies it with config overrides
      cfg.nested.val2 = '12345';

      // and: now it can validate
      const results = ConfigSchema.safeParse(cfg);
   });
});

Is anything like this possible or practical as a feature in zod? I think it is effectively a SafeParse that doesn’t do any checks, but instead just sets the default values on the object passed in.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
abierbaumcommented, Nov 5, 2020

@vriad That is brilliant!! Thank you so much for that idea. I think I have what I need to try it out.

I think we can close this out for now and I will work with this pattern.

0reactions
abierbaumcommented, Nov 6, 2020

Ran into one interesting issues. This pattern works to build up the schema, but the type of the schema returned by getSettingSchema includes the nullable. So if I try to infer the strict schema into a typescript type it still has the nulls involved.

const outputTest = getSettingsSchema('output');
type strict_type = z.infer<typeof outputTest>;

// ends up with strict_type equal to
type strict_type = {
    name: string | null;
    nested: {
        inner: number | null;
    };
}

I can probably still make this workable but would be great to find a way to infer the correct typescript type.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Step 3: Creating configuration profiles and feature flags
Attributes enable you to provide additional values within your flag. You can optionally validate attribute values against specified constraints. Constraints ...
Read more >
API Reference: ApolloServer - Apollo GraphQL Docs
You can use the ApolloServer class to create an instance of Apollo Server that you ... This feature can prevent certain GET requests...
Read more >
Advanced Usage — Requests 2.28.1 documentation
This document covers some of Requests more advanced features. Session Objects¶. The Session object allows you to persist certain parameters across requests. It ......
Read more >
Object.create() - JavaScript - MDN Web Docs
create () . With Object.create() , we can create objects with a designated prototype and also some properties. Note that the second parameter ......
Read more >
Merge requests API - GitLab Docs
Returns requests sorted in asc or desc order. Default is desc . source_branch, string, No, Returns merge requests with the given source branch....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found