當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。