How To Use / Reference Field Values Generated In The Same Json Schema
I am trying to create mock data by using the json-server in combination with the json-schema-faker. I was trying to use the $ref property but I understood that this only references
Solution 1:
I'd like to share here a solution that I found. In my case, I required to generate the same value for the fields password
and password_confirmation
using json-schema-faker
, and something that worked for me was, assign a new property in the faker library and put the new property name inside the faker schema. Here the code:
import faker from 'faker';
import jsf from 'json-schema-faker';
// here we generate a random password using faker
const password = faker.internet.password();
// we assign the password generated to a non-existent property, basically here you create your own property inside faker to save the constant value that you want to use.
faker.internet.samePassword = () => password;
// now we specify that we want to use faker in jsf
jsf.extend('faker', () => faker);
// we create the schema specifying the property that we have created above
const fakerSchema = {
type: 'object',
properties: {
password: {
faker: 'internet.samePassword',
type: 'string'
},
password_confirmation: {
faker: 'internet.samePassword',
type: 'string'
}
}
};
// We use the schema defined and voilá!
let dataToSave = await jsf.resolve(fakerSchema);
/*
This is the data generated
{
password: 'zajkBxZcV0CwrFs',
password_confirmation: 'zajkBxZcV0CwrFs'
}
*/
Post a Comment for "How To Use / Reference Field Values Generated In The Same Json Schema"