Giter VIP home page Giter VIP logo

nexus-validate's People

Contributors

filipstefansson avatar krolow avatar paolotiu avatar ysfaran avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

nexus-validate's Issues

TS type error

Type '({ string }: { string: any; }) => { email: any; }' has no properties in common with type 'ArgsValidationConfig<{ data: { name?: string; password?: string; }; }>'.ts(2559)

in code

args: {
    email: stringArg(),
},
validate: ({ string }) => ({
  email: string().email(),
}),

my ts version 4.4.3
nexus-validate 1.1.0

Yup transformers don't transform args

First off, thanks for building this, it's great! Just what I wanted from a Nexus validation package!

Sorry if this is a known limitation, but I noticed that yup transformers don't seem to impact what gets passed to the resolve function. For instance, in this code:

t.field("userSignUp", {
      type: UserAuthPayload,
      args: {
        email: nonNull(stringArg()),
        username: nonNull(stringArg()),
        password: nonNull(stringArg()),
      },
      validate: ({ string }) => ({
        email: string().email(),
        username: string().min(3).max(20).trim(),
        password: string().min(8),
      }),
      resolve: async (_root, { email, username, password }, ctx) => {
        ...
        const user = await ctx.prisma.user.create({
          data: { discriminator, email, passwordHash, username },
        });
        ...
        return { user };
      },

The username field can still contain leading/trailing spaces, even with the call to trim() in the validate function.

Pass nexus context to yup validate function

Problem

If you want to add a custom validation method to a yup schema you can use yup.addMethod:

yup.addMethod(yup.string, "currency", function () {
  return this.test(function(value){
    const currencies = ["€", "$"];
    const isCurrency = currencies.includes(value!);

    if (!isCurrency) {
      return this.createError({
        message: `${value} is not a valid currency, use on of [${currencies}]`,
      });
    }

    return true;
  });
});

Usage (you would need to add also global typings but it's not necessary to show this here):

validate(({ string }) => ({ currencyField: string().currency() }) 

The problem that I have is that my currencies are fetched once at startup from another backend. This means it's not static data. So I pass it to the graphl context, with apollo it would look like this:

const currencies = await getCurrenciesFromAPI(someConfig);

const server = new ApolloServer({
    context: () => ({ currencies }),
    // ...
 });

To break it down: currently you have no access to the context in "yup land".

Solution

The easiest way to solve this would be to pass the contex to yup.validate and change this line from:

await schema.validate(args);

to:

await schema.validate(args , { context: ctx };

Then you could implement the same currency method this way:

yup.addMethod(yup.string, "currency", function () {
  return this.test(async (value, testContext) => {
    const graphQLContext = testContext.options.context
    const isCurrency = graphQLContext.currencies.includes(value!);

    if (!isCurrency) {
      return this.createError({
        message: `${value} is not a valid currency, use on of [${currencies}]`,
      });
    }

    return true;
  });
});

I presented a relatively simple example but you could also use this to make database validation if your context contains a database client and much more.

Alternatives

You could alternatively also pass the context to the custom method everytime you use it:

validate(({ string }, args, ctx) => ({ currencyField: string().currency(ctx) }) 

But IMHO the solution above looks way cleaner and make this library more extensible. What do you think ? πŸ™‚

The automated release is failing 🚨

🚨 The automated release from the alpha branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the alpha branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Typescript error

Issue and Screenshot

When adding the validation VSCode keeps giving this typescript error
screenshot

Object literal may only specify known properties, and 'validate' does not exist in type 'NexusOutputFieldConfig<"Mutation", "signup">'.ts(2345)

The code is this and it works fine when running, it just gives the error in the editor without going away even after restarting the ts server and the editor.

Code

import { extendType, nonNull, stringArg } from "nexus";
import { Context } from "../context";

type AuthInput = {
  email: string;
  password: string;
};

export const SignupMutation = extendType({
  type: "Mutation",
  definition(t) {
    t.nonNull.field("signup", {
      type: "User",
      args: {
        email: nonNull(stringArg()),
        password: nonNull(stringArg()),
      },
      validate: ({ string }) => ({
        email: string().required().email().max(255),
        password: string().required().min(6).max(255),
      }),
      async resolve(_root, args: AuthInput, ctx: Context) {
        ...
      },
    });
  },
});

Versions

    "nexus": "^1.1.0",
    "nexus-prisma": "^0.35.0",
    "nexus-validate": "^1.2.0",
    "yup": "^0.32.11"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.