async function getJsonValidator()

in functions/index.js [15:45]


async function getJsonValidator() {
  console.log("Creating schema validator...")

  // first, try fetching latest schema from Firestore
  const db = admin.firestore();
  const latestSchema = await db.collection('glean_schemas').doc('latest').get();
  let schema;
  let schemaVersion;
  if (latestSchema.exists) {
    console.log('Using schema from Firestore');
    const data = latestSchema.data();
    schema = data.schema;
    schemaVersion = data.deployTimestamp;
  } else {
    // if there's no schema in Firestore, fall back to bundled one
    console.log("Using bundled schema");
    const readFile = util.promisify(fs.readFile);
    schema = await readFile('schema/glean.1.schema.json');
    schemaVersion = "bundled";
  }

  const gleanSchema = schema;

  const Ajv = require('ajv');
  const ajv = new Ajv({unknownFormats: ["datetime", "json"]});
  ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
  return {
    validator: ajv.compile(JSON.parse(gleanSchema.toString())),
    schemaVersion: schemaVersion,
  };
}