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


TypeScript ajv.compile函数代码示例

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


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

示例1: validateConfig

export function validateConfig(config: Config | string) {
  if (typeof config === 'string') {
    config = parse(config) as Config;
  }

  // fs.writeFileSync('__parsed.json', JSON.stringify(config, undefined, 2), 'utf8');

  const originalConfig = JSON.parse(JSON.stringify(config)) as Config;

  // new instance required for empty error list
  const ajv = new Ajv({ useDefaults: true, allErrors: true });
  const validate = ajv.compile(schema);

  // validate and apply default values from schema
  const valid = validate(config);
  if (!valid) {
    throw new Error(JSON.stringify(validate.errors, undefined, 2));
  }

  const internalConfig = getInternalConfig(config as any, originalConfig);

  // fs.writeFileSync('__validated.json', JSON.stringify(internalConfig, undefined, 2), 'utf8');

  return internalConfig;
}
开发者ID:igor-bezkrovny,项目名称:texturer,代码行数:25,代码来源:config.ts

示例2: createConfigValidator

async function createConfigValidator() {
  const ajv = new Ajv({allErrors: true, coerceTypes: true})
  ajv.addMetaSchema(require("ajv/lib/refs/json-schema-draft-04.json"))
  require("ajv-keywords")(ajv, ["typeof"])
  const schema = await readJson(path.join(__dirname, "..", "..", "scheme.json"))
  return ajv.compile(schema)
}
开发者ID:yuya-oc,项目名称:electron-builder,代码行数:7,代码来源:config.ts

示例3: describe

describe('OpListTest', () => {
  const jsonValidator = new ajv();
  const validator = jsonValidator.compile(schema);
  beforeEach(() => {});

  describe('validate schema', () => {
    // tslint:disable-next-line:no-any
    const mappersJson: any = {
      arithmetic,
      basicMath,
      convolution,
      creation,
      logical,
      image,
      graph,
      matrices,
      normalization,
      reduction,
      sliceJoin,
      transformation
    };
    Object.keys(mappersJson).forEach(key => {
      it('should satisfy the schema: ' + key, () => {
        const valid = validator(mappersJson[key]);
        if (!valid) console.log(validator.errors);
        expect(valid).toBeTruthy();
      });
    });
  });
});
开发者ID:oveddan,项目名称:tfjs-converter,代码行数:30,代码来源:op_list_test.ts

示例4: validator

  /**
   * A validator that uses the schema set for this reader.
   */
  protected get validator(): Ajv.ValidateFunction {
    if (this._validator === undefined) {
      const ajv = new Ajv();
      this._validator = ajv.compile(this.schema);
    }

    return this._validator;
  }
开发者ID:lddubeau,项目名称:wed,代码行数:11,代码来源:metadata-json-reader.ts

示例5: constructor

	constructor(schema: IJSONSchema, options?: AJV.Options) {
		this.schema = schema;
		const ajv = new AJV({
			allErrors: true,
			coerceTypes: true,
			removeAdditional: true,
			useDefaults: true,
			...options
		});
		const validate = ajv.compile(schema);

		this._validate = validate;
	}
开发者ID:classbook,项目名称:Class-UI,代码行数:13,代码来源:Schema.ts

示例6: renderManager

// Function `renderManager(element, tag)` creates a widget embed manager for the
// specified <script> tag (which must have mime type)
//     "application/vnd.jupyter.widget-state+json".
// Then it performs a look up of all script tags under the specified DOM
// element with the mime type
//     "application/vnd.jupyter.widget-view+json".
// For each oone of these <script> tag, if the contained json specifies a model id
// known to the aforementioned manager, it is replaced with a view of the model.
//
// Besides, if the view script tag has an <img> sibling DOM node with class `jupyter-widget`,
// the <img> tag is deleted.
function renderManager(element, tag) {
    var widgetStateObject = JSON.parse(tag.innerHTML);
    var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}
    var model_validate = ajv.compile(widget_state_schema);
    var valid = model_validate(widgetStateObject);
    if (!valid) {
        console.log(model_validate.errors);
    }
    var manager = new embed.EmbedManager();
    manager.set_state(widgetStateObject.state, {}).then(function(models) {
        var tags = element.querySelectorAll('script[type="application/vnd.jupyter.widget-view+json"]');
        for (var i=0; i!=tags.length; ++i) {
            // TODO: validate view schema
            let viewtag = tags[i];
            let widgetViewObject = JSON.parse(viewtag.innerHTML);
            var view_validate = ajv.compile(widget_view_schema);
            var valid = view_validate(widgetViewObject);
            if (!valid) {
                console.log(view_validate.errors);
            }
            let model_id = widgetViewObject.model_id;
            let model = models.find(function(item) {
                return item.id == model_id;
            });
            if (model !== undefined) {
                if (viewtag.previousElementSibling &&
                    viewtag.previousElementSibling.matches('img.jupyter-widget')) {
                    viewtag.parentElement.removeChild(viewtag.previousElementSibling);
                }
                let widgetTag = document.createElement('div');
                widgetTag.className = 'widget-subarea';
                viewtag.parentElement.insertBefore(widgetTag, viewtag);
                manager.display_model(undefined, model, { el : widgetTag });
            }
        }
    });
}
开发者ID:cameronoelsen,项目名称:ipywidgets,代码行数:48,代码来源:embed-webpack.ts

示例7: require

});

var metaSchema = require('ajv/lib/refs/json-schema-draft-04.json');
ajv.addMetaSchema(metaSchema);
ajv._opts.defaultMeta = metaSchema.id;

// optional, using unversioned URI is out of spec, see https://github.com/json-schema-org/json-schema-spec/issues/216
ajv._refs['http://json-schema.org/schema'] = 'http://json-schema.org/draft-04/schema';

// Optionally you can also disable keywords defined in draft-06
ajv.removeKeyword('propertyNames');
ajv.removeKeyword('contains');
ajv.removeKeyword('const');
// END: Ajv config for json-schema draft 4, from https://github.com/epoberezkin/ajv/releases/tag/5.0.0

let model_validate = ajv.compile(widget_state_schema);
let view_validate = ajv.compile(widget_view_schema);


// `LoadInlineWidget` is the main function called on load of the web page.
// All it does is inserting a <script> tag for requirejs in the case it is not
// available and call `renderInlineWidgets`
function loadInlineWidgets(event) {
    let loadRequire = new Promise(function(resolve, reject) {
        if ((window as any).requirejs) {
            resolve();
        } else {
            // If requirejs is not on the page on page load, load it from cdn.
            let scriptjs = require('scriptjs') as any;
            scriptjs('https://unpkg.com/requirejs/require.js', function() {
                resolve();
开发者ID:mmeanwe,项目名称:ipywidgets,代码行数:31,代码来源:embed-webpack.ts

示例8: require

import * as Ajv from 'ajv'
import * as yaml from 'js-yaml'
import * as fs from 'fs-extra'
import schema = require('prisma-json-schema/dist/schema.json')
import { PrismaDefinition } from 'prisma-json-schema'
import { Variables } from './Variables'
import { Args } from './types/common'
import { Output, IOutput } from './Output'
const debug = require('debug')('yaml')
import * as stringify from 'json-stable-stringify'
import chalk from 'chalk'

const ajv = new Ajv()

const validate = ajv.compile(schema)
// this is used by the playground, which accepts additional properties
const validateGraceful = ajv.compile({ ...schema, additionalProperties: true })

const cache = {}

export async function readDefinition(
  filePath: string,
  args: Args,
  out: IOutput = new Output(),
  envVars?: any,
  graceful?: boolean,
): Promise<{ definition: PrismaDefinition; rawJson: any }> {
  if (!fs.pathExistsSync(filePath)) {
    throw new Error(`${filePath} could not be found.`)
  }
  const file = fs.readFileSync(filePath, 'utf-8')
开发者ID:dhruvcodeword,项目名称:prisma,代码行数:31,代码来源:yaml.ts

示例9: require

import Ajv from "ajv";
import { Logger } /* supplied by @types/embark in packages/embark-typings */ from "embark";
import {__} from "i18n";
import { schema } from "./schema";
const fs = require("fs");

const ajv = new Ajv();
const scaffoldingSchema = ajv.compile(schema);

interface Properties {
  [propertyName: string]: string;
}

interface Data {
  [contractName: string]: Properties;
}

const ASSOCIATIONS = ["belongsTo", "hasMany"];
const IPFS = ["ipfsText", "ipfsImage"];

export class SmartContractsRecipe {
  public data: Data;
  constructor(private readonly logger: Logger,
              private readonly contractOrFile: string,
              private readonly fields: string[],
             ) {
    if (fs.existsSync(contractOrFile)) {
      this.data = fs.readJSONSync(contractOrFile);
    } else {
      this.data = this.build();
    }
开发者ID:iurimatias,项目名称:embark-framework,代码行数:31,代码来源:smartContractsRecipe.ts

示例10: require

import * as Ajv from 'ajv'
import * as yaml from 'js-yaml'
import * as fs from 'fs-extra'
import schema = require('prisma-json-schema/dist/schema.json')
import { PrismaDefinition } from 'prisma-json-schema'
import { Variables } from './Variables'
import { Args } from './types/common'
import { Output, IOutput } from './Output'
const debug = require('debug')('yaml')
import * as stringify from 'json-stable-stringify'
import chalk from 'chalk'

const ajv = new Ajv()

const validate = ajv.compile(schema)

const cache = {}

export async function readDefinition(
  filePath: string,
  args: Args,
  out: IOutput = new Output(),
  envVars?: any,
): Promise<{ definition: PrismaDefinition; rawJson: any }> {
  if (!fs.pathExistsSync(filePath)) {
    throw new Error(`${filePath} could not be found.`)
  }
  const file = fs.readFileSync(filePath, 'utf-8')
  const json = yaml.safeLoad(file) as PrismaDefinition
  // we need this copy because populateJson runs inplace
  const jsonCopy = { ...json }
开发者ID:nunsie,项目名称:prisma,代码行数:31,代码来源:yaml.ts


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