Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

schema-magic

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

schema-magic - npm Package Compare versions

Comparing version 0.0.3 to 0.0.6

lib/formatters.js

2

index.js

@@ -1,2 +0,2 @@

module.exports=require('./lib');
module.exports=require('./lib/index.js');

@@ -0,3 +1,4 @@

const $json=require('json-magic');
const $deepcopy=require('deepcopy');
const $json=require('json-magic');
const $ajv=require('ajv');
const $check=require('check-types');

@@ -8,46 +9,169 @@ const $types=require('type-magic');

const _sqlTypeMapping=[
{
type:"string",
sqlType:"varchar(255)",
},
{
type:"integer",
sqlType:"int",
},
{
type:"boolean",
sqlType:"bit",
},
{
type:"string",
format:"date-time",
sqlType:"datetime",
const Validator=require('./Validator.js');
},
{
type:"string",
format:"date",
sqlType:"date",
const _jsonSchema=require("./jsonSchema.json");
const _jsonPatchSchema=require("./jsonPatch.json");
const _sqlTypeMapping=require('./SQLTypeMappings.json');
const _keywords=require("./keywords.js");
const _formatters=require("./formatters.js");
},
{
type:"array",
sqlType:"varchar(255)",
const _ajv = $ajv({
format:"full"
});
},
{
type:"object",
sqlType:"varchar(255)",
_ajv.addMetaSchema(_jsonSchema);
},
{
type:"null",
sqlType:"varchar(255)",
const _ajvCoerce = $ajv({
format:"full",
coerceTypes:true
});
_ajvCoerce.addMetaSchema(_jsonSchema);
require('ajv-keywords')(_ajv, ['switch']);
require('ajv-keywords')(_ajvCoerce, ['switch']);
for (let k in _formatters){
if(!_formatters.hasOwnProperty(k)){
continue;
}
];
_ajv.addFormat(k,_formatters[k]);
_ajvCoerce.addFormat(k,_formatters[k]);
}
class SchemaMagic {
for (let k in _keywords){
if(!_keywords.hasOwnProperty(k)){
continue;
}
_ajv.addKeyword(k,_keywords[k]);
_ajvCoerce.addKeyword(k,_keywords[k]);
}
class SchemaMagic{
static validate(document,schema,coerce){
//argument checks
if (!document){throw new Error("No Document specified");}
if (!schema){throw new Error("No Schema specified");}
let localAjv=_ajv;
if (coerce)localAjv=_ajvCoerce;
let valid=true;
try{
valid=localAjv.validate(schema, document)
}
catch(exp){
return {message:"Invalid Schema","Error":exp.message};
}
if (!valid){
let retErr=localAjv.errors.map(function(doc){
return {
message:doc.message,
dataPath:doc.dataPath,
keyword:doc.keyword,
schemaPath:doc.schemaPath
}
});
return retErr;
}
else
{
return null;
}
}
static validateWithParameters(document,schema,options){
let paramPaths=[];
options=options||{};
if (!options.paramIdentifier)options.paramIdentifier='@';
$json.walk(document, (value,path) =>{
if (value&&value.substring){
if (value.substring(0,1)===options.paramIdentifier){
paramPaths.push(path);
}
}
},'.');
if (paramPaths.length>0){
let workingSchema=$deepcopy(schema);
for (let paramPath of paramPaths){
let splitPaths=paramPath.split('.');
let schemaPaths=[];
let suffix="";
let isArray=false;
for (let splitPath of splitPaths){
if (!isNaN(parseInt(splitPath))){
schemaPaths.push("items");
suffix=".type";
isArray=true;
}else{
schemaPaths.push("properties." + splitPath);
}
}
let schemaPath=schemaPaths.join('.') + suffix;
try{
let curSchema=$json.get(workingSchema,schemaPath);
let replacement={type:"string"};
if (isArray)replacement=[curSchema,"string"];
$json.set(workingSchema,schemaPath,replacement);
}catch (exp){
//path does not exist, ignore...
}
}
return SchemaMagic.validate(document,workingSchema,options.coerce);
}else{
return SchemaMagic.validate(document,schema,options.coerce);
}
}
static copy(schema){
if (!schema){throw new Error("No Schema specified")}
return $deepcopy(schema);
}
static coerceData(data,schema){
if (!data)return null;
if (!schema){throw new Error("No Schema specified")}
function pathToPointer(path){
path=path.replace("$","");
var retArr=[];
path.replace(/\[(.+?)\]/g, function($0, $1) { retArr.push($1.replace("'","").replace("'","")) })
return "/" + retArr.join("/");
}
var coerceFields=null;
if(schema.coerceFields){
coerceFields=schema.coerceFields;
}else{
coerceFields=SchemaMagic.getCoerceFields(schema);
}
for (var i=0;i<coerceFields.length;i++){
var values=jsonPath.eval(data,coerceFields[i].path,{resultType:"PATH"}) ;
for (var j=0;j<values.length;j++){
var pointer=pathToPointer(values[j]);
var value=$json.get(data,pointer);
$json.set(data,pointer,new Date(value));
//
}
}
return data;
}
//flattens a schema returning an array of paths to access elements of an object

@@ -147,3 +271,3 @@ static flattenSchema(schema,options){

return "CREATE TABLE " + charFunc(options.schema) + "." + charFunc(tableName) + "(\r\n" +
cols.join(",\r\n") + ");"
cols.join(",\r\n") + ");"
}

@@ -252,4 +376,90 @@

static normalizeSchema(schema,options,depth){
if (!schema){throw new Error("No Schema specified")}
let propPaths=[];
let workingSchema=schema;
if (!options)options={};
if (options.copy)
workingSchema=$deepcopy(schema);
$json.walk(schema,function(value,path){
let parsedPath=$json.parsePath(path);
if (parsedPath[parsedPath.length-1]==='$ref'){
parsedPath.pop();
propPaths.push({
path:$json.compilePath(parsedPath),
ref:value?value.substring(1):null
});
}
});
for (let propPath of propPaths){
let repVal=$json.get(workingSchema,propPath.ref);
$json.set(workingSchema,propPath.path,repVal);
}
if (!depth)depth=0;
if (depth<1){
depth++;
workingSchema=SchemaMagic.normalizeSchema(workingSchema,null,depth);
}
if (options.deleteDefinitions)
delete workingSchema.definitions;
//do it again
return workingSchema;
}
static getCoerceFields(schema){
if (!schema){throw new Error("No Schema specified");}
let coerceFields=[];
getFieldsRecursive(schema.properties,"$","");
function getFieldsRecursive(obj,currentPath,currentPointer) {
for(let key in obj) {
if(!obj.hasOwnProperty(key)){
continue;
}
if (obj[key].type === "object" ) {
if (obj[key].properties){
getFieldsRecursive(obj[key].properties, currentPath + "." + key,currentPointer + "/" + key);
}
}else if (obj[key].type === "array" && obj[key].items && obj[key].items.type==="object" ) {
getFieldsRecursive(obj[key].items.properties, currentPath + "." + key + "[*]", currentPointer + "/" + key + "[*]");
}else{
if (obj[key].format && obj[key].format==="date-time"){
coerceFields.push({
path:currentPath + "." + key,
updatePath:currentPointer + "/" + key,
format:obj[key].format
});
}
}
}
}
return coerceFields;
}
static get coreSchemas(){
return{
jsonSchema:_jsonSchema,
jsonPatch:_jsonPatchSchema
}
}
static get sqlTypeMappings(){
return _sqlTypeMapping;
}
static get Validator(){
return Validator;
}
}
module.exports=SchemaMagic;
{
"name": "schema-magic",
"version": "0.0.3",
"version": "0.0.6",
"description": "JSON Schema Utilities",

@@ -10,8 +10,14 @@ "author": {

"dependencies": {
"check-types": "7.3.0",
"deepcopy": "0.6.3",
"json-magic": "0.0.5",
"type-magic": "0.0.1",
"underscore": "1.9.0",
"underscore.string": "3.3.4"
"ajv": "6.10.0",
"ajv-keywords": "3.4.0",
"bson-objectid": "1.2.5",
"check-types": "8.0.2",
"cron-parser": "2.11.0",
"deepcopy": "2.0.0",
"json-magic": "0.0.8",
"moment": "2.24.0",
"moment-timezone": "0.5.25",
"type-magic": "0.0.2",
"underscore": "1.9.1",
"underscore.string": "3.3.5"
},

@@ -18,0 +24,0 @@ "engines": {

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc