当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript joi.validate函数代码示例

本文整理汇总了TypeScript中joi.validate函数的典型用法代码示例。如果您正苦于以下问题:TypeScript validate函数的具体用法?TypeScript validate怎么用?TypeScript validate使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了validate函数的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: function

        app[config.method.toLowerCase()](config.path, async function (req: RouterRequest, res: RouterResponse, next: NextFunction) {
            // Shim the request and response objects with expected properties.
            req.domainWithProtocol = `${req.protocol}://${req.hostname}` + (req.hostname === "localhost" ? ":3000" : "");
            req.app = Object.assign({registeredRoutes}, req.app);

            if (config.bodyValidation) {
                const validation = validate(req.body, config.bodyValidation);

                if (validation.error) {
                    const error = badData(validation.error.message, validation.error.details);

                    return next(error);
                }

                req.validatedBody = validation.value;
            }

            if (config.queryValidation) {
                const validation = validate(req.query, config.queryValidation);

                if (validation.error) {
                    const error = badData(validation.error.message, validation.error.details);

                    return next(error);
                }

                req.validatedQuery = validation.value;
            }

            if (config.paramValidation) {
                const validation = validate(req.params, config.paramValidation);

                if (validation.error) {
                    const error = badData(validation.error.message, validation.error.details);

                    return next(error);
                }

                req.validatedParams = validation.value;
            }

            // Pass control to the route's handler. Handlers can be async, so wrap them in try/catch to handle promise rejections.
            try {
                const handler = config.handler(req, res, next);

                if (handler instanceof Promise) {
                    await handler;
                }

                return;
            } catch (e) {
                return next(e);
            }
        });
开发者ID:nozzlegear,项目名称:fuselage,代码行数:54,代码来源:index.ts

示例2: validate

 public validate(): boolean {
   var res = Joi.validate(this.config, schema);
   if (res.error) {
     throw res.error;
   }
   return true;
 }
开发者ID:tomvlk,项目名称:ManiaJS,代码行数:7,代码来源:configuration.ts

示例3: createUser

export function createUser(req: Request, res: Response, next: NextFunction) {
  const schema = Joi.object().keys({
    name: Joi.string().min(3).required(),
    email: Joi.string().email().required(),
    password: Joi.string().required().regex(passwordRegex),
    agreeTos: Joi.boolean().only(true).required(),
    referral: Joi.string().email().options({
      language: {
        key: '{{!label}}',
        string: {
          email: 'Not valid referral code'
        }
      }
    }).label(' ') // Joi does not allow empty label but space is working
  });

  if (req.body.referral) {
    req.body.referral = base64decode(req.body.referral);
  }

  const result = Joi.validate(req.body, schema, options);

  if (result.error) {
    return res.status(422).json(result);
  } else {
    return next();
  }
}
开发者ID:Norestlabs-Mariya,项目名称:backend-ico-dashboard,代码行数:28,代码来源:request.validation.ts

示例4: it

            it('required only', () => {
                let obj = {
                    hello: 'world'
                };

                expect(Joi.validate(obj, this.schema).error).toBeNull();
            });
开发者ID:richie5um,项目名称:TESTJoi,代码行数:7,代码来源:joi.spec.ts

示例5: joiValidate

export function joiValidate(value: any, validator: SchemaLike): ValidationError | null {

    let validationResult = validate(value, validator, {
        abortEarly: false,
        allowUnknown: false
    });

    if (validationResult.error) {

        let duplicates: any = {};
        validationResult.error.details = validationResult.error.details.filter((detail) => {
            if (duplicates[detail.message] || detail.type === "object.allowUnknown")
                return false;
            else {
                duplicates[detail.message] = true;
                return true;
            }
        });

        if (validationResult.error.details.length === 0)
            return null;
        else
            return validationResult.error;
    }
    else
        return null;

}
开发者ID:KostiaSA,项目名称:BuhtaClient2019,代码行数:28,代码来源:joiValidate.ts

示例6: setup

export async function setup(server: Server, request: Request, reply: IReply)
{
    let payload = request.payload as {shopUrl: string};
    const props: SetupProps = {
        title: "Connect your Shopify store.",
        shopUrl: payload.shopUrl,
    };
    const validation = joi.validate(payload, setupValidation);
    
    if (validation.error)
    {
        props.error = humanizeError(validation.error);
        
        return reply.view("setup/setup.js", props);
    }
    
    payload = validation.value;
    
    if (! (await isValidShopifyDomain(payload.shopUrl)))
    {
        props.error = "It looks like the URL you entered is not a valid Shopify domain.";
        
        return reply.view("setup/setup.js", props);
    }
    
    const scopes: Enums.AuthScope[] = ["write_script_tags"]
    const redirect = `${getRequestProtocol(request)}://${getDomain(true)}${ConnectRoutes.GetShopify}`.toLowerCase();
    const oauthUrl = await buildAuthorizationUrl(scopes, payload.shopUrl, ShopifyApiKey, redirect);

    return reply.redirect(oauthUrl);
}
开发者ID:yashodhank,项目名称:deliver-on,代码行数:31,代码来源:setup-routes.ts

示例7: validateDevice

export function validateDevice(state: State, device: Device): Device {
  if (device.interfaceIds) {
    validateInterfaces(state, device.interfaceIds)
  }
  const deviceClass = state.deviceClasses[device.deviceClassId]
  if (!deviceClass) {
    throw raxaError({
      type: 'missingDeviceClass',
      deviceClassId: device.deviceClassId,
    })
  }
  if (!deviceClass.config) {
    if (device.config) throw new Error('no config allowed')
    return device
  }
  const joiSchema = joi.object({
    id: joi.string().allow(''),
    name: joi.string().required(),
    pluginId: joi.string().required(),
    deviceClassId: joi.string().required(),
    config: propertiesToJoi(deviceClass.config),
    interfaceIds: joi.array().items(joi.string().required()),
  })
  const result = joi.validate(device, joiSchema)
  if (result.error) {
    throw raxaError({type: 'invalidDevice', joiError: result.error})
  }

  return result.value
}
开发者ID:Pajn,项目名称:RAXA,代码行数:30,代码来源:validations.ts

示例8:

 set: (v) => {
   const vr = joi.validate(v, rule)
   if (vr.error) {
     throw vr.error
   }
   descriptor.set(v);
 },
开发者ID:tes,项目名称:resource-backup-tool,代码行数:7,代码来源:joid.ts

示例9: validateInput

  private validateInput(envConfig: EnvConfig): EnvConfig {
    const envVarsSchema: Joi.ObjectSchema = Joi.object({
      NODE_ENV: Joi.string()
        .valid(['development', 'production', 'test', 'provision'])
        .default('development'),
      PORT: Joi.number().default(3000),
      JWT_SECRET: Joi.string().required(),
      JWT_EXPIRE: Joi.number().default(3600 * 24 * 7),
      DB_TYPE: Joi.string().default('mysql'),
      DB_HOST: Joi.string().default('localhost'),
      DB_PORT: Joi.number().default(3306),
      DB_USERNAME: Joi.string().required(),
      DB_PASSWORD: Joi.string().required(),
      DB_DATABASE_NAME: Joi.string().required(),
    });

    const { error, value: validatedEnvConfig } = Joi.validate(
      envConfig,
      envVarsSchema,
    );
    if (error) {
      throw new Error(`Config validation error: ${error.message}`);
    }
    return validatedEnvConfig;
  }
开发者ID:CaptainShisha,项目名称:REST-API,代码行数:25,代码来源:config.service.ts


注:本文中的joi.validate函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。