Aaron Benton is an experienced architect who specializes in creative solutions to develop innovative mobile applications. He has over 10 years experience in full stack development, including ColdFusion, SQL, NoSQL, JavaScript, HTML, and CSS. Aaron is currently an Applications Architect for Shop.com in Greensboro, North Carolina and is a Couchbase Community Champion.

FakeIt Series 4 of 5: Working with Existing Data
So far in our FakeIt series we’ve seen how we can Generate Fake Data, Share Data and Dependencies, and use Definitions for smaller models. Today we are going to look at the last major feature of FakeIt, which is working with existing data through inputs.
Rarely as developers do we get the advantage of working on greenfield applications, our domains are more often than not a comprised of different legacy databases and applications. As we are modeling and building new applications, we need to reference and use this existing data. FakeIt allows you to provide existing data to your models through JSON, CSV or CSON files. This data is exposed as an inputs variable in each of a models *run and *build functions.
Users Model
We will start with our users.yaml model that we updated to in our most recent post to use Address y Phone definitions.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
nombre: Users tipo: objeto clave: _id datos: mín: 1000 máximo: 2000 properties: _id: tipo: cadena descripción: El documento identificación built by el prefix “user_” y el users identificación datos: post_build: “`user_${this.user_id}`” doc_type: tipo: cadena descripción: El documento tipo datos: valor: “user” ID de usuario: tipo: integer descripción: An auto–incrementing number datos: build: documento_index first_name: tipo: cadena descripción: El users first nombre datos: build: faker.nombre.firstName() last_name: tipo: cadena descripción: El users last nombre datos: build: faker.nombre.lastName() nombre de usuario: tipo: cadena descripción: El nombre de usuario datos: build: faker.internet.nombreDeUsuario() contraseña: tipo: cadena descripción: El users contraseña datos: build: faker.internet.contraseña() email_address: tipo: cadena descripción: El users email address datos: build: faker.internet.email() created_on: tipo: integer descripción: An epoch time of when el usuario was created datos: build: nuevo Date(faker.fecha.past()).getTime() addresses: tipo: objeto descripción: An objeto containing el home y work addresses para el usuario properties: home: descripción: El users home address schema: $ref: ‘#/definitions/Address’ work: descripción: El users work address schema: $ref: ‘#/definitions/Address’ main_phone: descripción: El users main phone number schema: $ref: ‘#/definitions/Phone’ datos: post_build: | eliminar este.main_phone.tipo regresar este.main_phone additional_phones: tipo: matriz descripción: El users additional phone numbers elementos: $ref: ‘#/definitions/Phone’ datos: mín: 1 máximo: 4 definitions: Phone: tipo: objeto properties: tipo: tipo: cadena descripción: El phone tipo datos: build: faker.random.arrayElement([ ‘Home’, ‘Work’, ‘Mobile’, ‘Other’ ]) phone_number: tipo: cadena descripción: El phone number datos: build: faker.phone.phoneNumber().replace(/[^0–9]+/g, ”) extension: tipo: cadena descripción: El phone extension datos: build: chance.bool({ likelihood: 30 }) ? chance.integer({ mín: 1000, máximo: 9999 }) : nulo Address: tipo: objeto properties: address_1: tipo: cadena descripción: El address 1 datos: build: `${faker.address.streetAddress()} ${faker.address.streetSuffix()}` address_2: tipo: cadena descripción: El address 2 datos: build: chance.bool({ likelihood: 35 }) ? faker.address.secondaryAddress() : nulo locality: tipo: cadena descripción: El ciudad / locality datos: build: faker.address.ciudad() región: tipo: cadena descripción: El región / state / province datos: build: faker.address.stateAbbr() postal_code: tipo: cadena descripción: El zip code / postal code datos: build: faker.address.zipCode() country: tipo: cadena descripción: El country code datos: build: faker.address.countryCode() |
Currently, our Address definition is generating a random country. What if our ecommerce site only supports a small subset of the 195 countries? Let’s say we support six countries to start with: US, CA, MX, UK, ES, DE. We could update the definitions country property to grab a random array element:
(For brevity the other properties have been left off of the model definition)
|
1 2 3 4 5 6 |
... country: tipo: cadena descripción: El country code datos: build: faker.random.arrayElement([‘US’, ‘CA’, ‘MX’, ‘UK’, ‘ES’, ‘DE’]); |
While this would work, what if we have other models that rely on this same country info, we would have to duplicate this logic. We can achieve this same thing by creating a countries.json file, and adding an inputs property to the data property that can be an absolute or relative path to our input. When are model is generated, our countries.json file will be exposed to each of the models build functions via the inputs argument as inputs.countries
(For brevity the other properties have been left off of the model definition)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
nombre: Users tipo: objeto clave: _id datos: mín: 1000 máximo: 2000 inputs: ./countries.json properties: ... definitions: ... country: tipo: cadena descripción: El country code datos: build: faker.random.arrayElement(inputs.countries); countries.json [ “US”, “CA”, “MX”, “UK”, “ES”, “DE” ] |
By changing one existing line and adding another line in model we have provided existing data to our Users model. We can still generate a random country, based on the countries our application supports. Lets test our changes by using the following command:
|
1 |
fakeit console —count 1 models/users.yaml |

Products Model
Our ecommerce application is using a separate system for categorization, we need to expose that data to our randomly generated products so that we are using valid category information. We will start with the products.yaml that we defined in the FakeIt Series 2 of 5: Shared Data and Dependencies post.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
products.yaml nombre: Productos tipo: objeto clave: _id datos: mín: 4000 máximo: 5000 properties: _id: tipo: cadena descripción: El documento identificación datos: post_build: `product_${este.product_id}` doc_type: tipo: cadena descripción: El documento tipo datos: valor: product product_id: tipo: cadena descripción: Unique identifier representing a specific product datos: build: faker.random.uuid() price: tipo: double descripción: El product price datos: build: chance.floating({ mín: 0, máximo: 150, fixed: 2 }) sale_price: tipo: double descripción: El product price datos: post_build: | let sale_price = 0; si (chance.bool({ likelihood: 30 })) { sale_price = chance.floating({ mín: 0, máximo: este.price * chance.floating({ mín: 0, máximo: 0.99, fixed: 2 }), fixed: 2 }); } regresar sale_price; display_name: tipo: cadena descripción: Display nombre of product. datos: build: faker.commerce.productName() short_description: tipo: cadena descripción: Description of product. datos: build: faker.lorem.paragraphs(1) long_description: tipo: cadena descripción: Description of product. datos: build: faker.lorem.paragraphs(5) keywords: tipo: matriz descripción: An matriz of keywords elementos: tipo: cadena datos: mín: 0 máximo: 10 build: faker.random.word() availability: tipo: cadena descripción: El availability status of el product datos: build: | let availability = ‘In-Stock’; si (chance.bool({ likelihood: 40 })) { availability = faker.random.arrayElement([ ‘Preorder’, ‘Out of Stock’, ‘Discontinued’ ]); } regresar availability; availability_date: tipo: integer descripción: An epoch time of when el product is available datos: build: faker.fecha.recent() post_build: nuevo Date(este.availability_date).getTime() product_slug: tipo: cadena descripción: El URL friendly versión of el product nombre datos: post_build: faker.helpers.slugify(este.display_name).toLowerCase() category: tipo: cadena descripción: Categoría para el Product datos: build: faker.commerce.department() category_slug: tipo: cadena descripción: El URL friendly versión of el category nombre datos: post_build: faker.helpers.slugify(este.category).toLowerCase() image: tipo: cadena descripción: Image URL representing el product. datos: build: faker.image.image() alternate_images: tipo: matriz descripción: An matriz of alternate images para el product elementos: tipo: cadena datos: mín: 0 máximo: 4 build: faker.image.image() |
Our existing categories data has been provided in CSV format.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
categories.csv “category_id”,“category_name”,“category_slug” 23,“Electronics”,“electronics” 1032,“Office Supplies”,“office-supplies” 983,“Clothing & Apparel”,“clothing-and-apparel” 483,“Movies, Music & Books”,“movies-music-and-books” 3023,“Sports & Fitness”,“sports-and-fitness” 4935,“Automotive”,“automotive” 923,“Tools”,“tools” 5782,“Home Furniture”,“home-furniture” 9783,“Health & Beauty”,“health-and-beauty” 2537,“Toys”,“toys” 10,“Video Games”,“video-games” 736,“Pet Supplies”,“pet-supplies” |
Now we need to update our products.yaml model to use this existing data.
(For brevity the other properties have been left off of the model definition)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
nombre: Productos tipo: objeto clave: _id datos: mín: 4000 máximo: 5000 inputs: – ./categories.csv pre_build: globals.current_category = faker.random.arrayElement(inputs.categories); properties: ... category_id: tipo: integer descripción: El Categoría ID para el Product datos: build: globals.current_category.category_identificación category: tipo: cadena descripción: Categoría para el Product datos: build: globals.current_category.category_nombre category_slug: tipo: cadena descripción: El URL friendly versión of el category nombre datos: post_build: globals.current_category.category_slug ... |
There are a few things to notice about how we’ve updated our products.yaml model.
- inputs: is defined as an array not a string. While we are only using a single input, you can provide as many input files to your model as necessary.
- A pre_build function is defined at the root of the model. This is because we cannot grab a random array element for each of our three category properties as the values would not match. Each time an individual document is generated for our model, this pre_build function will run first.
- Each of our category properties build functions reference the global variable set by the pre_build function on our model.
We can test our changes by using the following command:
|
1 |
fakeit console —count 1 models/products.yaml |

Conclusión
Being able to work with existing data is an extremely powerful feature of FakeIt. It can be used to maintain the integrity of randomly generated documents to work with existing system, and can even be used to transform existing data and import it into Couchbase Server.
Up Next
Previous
- FakeIt Series 1 of 5: Generating Fake Data
- FakeIt Series 2 of 5: Shared Data and Dependencies
- FakeIt Series 3 of 5: Lean Models through Definitions

This post is part of the Couchbase Community Writing Program

Deja un comentario
Lo siento, debes estar conectado para publicar un comentario.