Build Status

MockData CFC

This is a ColdFusion version of the MockData Node.js service.

MockData is a simple service to generate fake JSON data as a JSON REST service, a ColdBox Module or a simple CFC Service API. The idea being that you may be offline, may not have access to an API, or simply need some fake data to test on your front end or seed a complete database with fake data.

MockDataCFC allows you to define the return JSON model in a very deterministic and simple modeling DSL. Read on 🚀 for some modeling goodness!

Requirements

  • ColdFusion 11+
  • Lucee 4.5+

Installation

Leverage CommandBox and type box install mockdatacfc

Usage

Once installed you can leverage it in different ways:

  1. CFC : Install it into your CFML application, instantiate the MockData.cfc and call the mock method using the mocking argument DSL: new mockdatacfc.models.MockData().mock().
  2. REST Service : Startup a CommandBox server in the root of the package once installed (box server start) and execute it via port: 3000. You can execute GET commands and pass the mocking DSL via the query string or execute a POST command with the mocking DSL as the body in JSON.
  3. ColdBox Module : Install it via CommandBox in a ColdBox app and hit the service via /mockdataCFC with a GET using the query string mocking DSL or a POST using the mocking DSL as the body in JSON. You can also get access to the mocking instance via the WireBox ID: [email protected] and call the mock method using the mocking argument DSL.

Customizing the service port

To specify a port or change the port, just add it an argument to the server start command or modify the server.json port configuration to your liking. You can even add SSL if you need to.

box server start port=XXXX

Getting Data

To get data from the REST service, point your XHR or cfhttp calls to the following entry points and either pass the mocking DSL via the query string or as a JSON POST body.

# Standalone Service
http://localhost:3000/

# ColdBox Module Service
http://localhost:8080/mockdataCFC

By default it will produce a glorious array of 10 objects of nothing! Since we did not specify any modeling data. So let's continue.

Note: MockData uses CORS so if you're running a virtual domain then you will still be able to hit the service.(As long as you have a decent browser.)

Number of objects

The number of objects to be returned by the service is determined by the $num argument, which defaults to 10 items:

# service call
http://localhost:3000/?$num=5

# ColdBox Module Service
http://localhost:8080/mockdataCFC?$num=5

# Module API
var data = getInstance( "[email protected]" )
    .mock(
        $num = 5
    );

Random Numbers

You can also specify a random return number by using the following forms:

  • $num:rand: 10 - A random number between 1-10.
  • $num:rand: 5:20 - A random number between 5-20.
# service call
http://localhost:3000/?$num=rand:10

# ColdBox Module Service
http://localhost:8080/mockdataCFC?$num=rand:10

# object
var data = getInstance( "[email protected]" )
    .mock(
        $num = "rnd:10: 20"
    );

Available Mocking Types

The available types MockDataCFC supports are:

  • age: Generates a random "adult" age of 18 to 75.
  • all_age: Generates a random age of 1 to 100.
  • autoincrement : Returns an incremented index starting from 1
  • baconlorem: Returns bacon lorem ipsum text. If used as baconlorem:N, returns N paragraphs. If used as baconlorem❌ Y, returns a random number of paragraphs between X and Y.
  • date: Generates a random date
  • datetime: Generates a random date and time value
  • email: Generates a random email.
  • fname: Generates a random first name.
  • name: Generates a random name.
  • lname: Generates a random last name.
  • lorem: Returns lorem ipsum text. If used as lorem:N, returns N paragraphs. If used as lorem❌ Y, returns a random number of paragraphs between X and Y.
  • num: By default, a number from 1 to 10. You can also use the form num:X for a random number between 1 and X. Or num❌ Y for a random number between X and Y.
  • oneof❌ y: Requires you to pass N values after it delimited by a colon. Example: oneof:male: female. Will return a random value from that list.
  • rnd:N, rand:N, rnd❌ y, rand❌ y : Generate random numbers with a specific range or range cap.
  • sentence: Generates a sentences. If used as sentence:N, returns N sentences. If used as sentence❌ Y, returns a random number of sentences beetween X and Y.
  • ssn: Generates a random Social Security number.
  • string: Just returns the word string
  • tel: Generates a random (American) telephone number.
  • uuid: Generates a random UUID
  • words: Generates a single word. If used as word:N, returns N words. If used as words❌ Y, returns a random number of words beetween X and Y.

Mocking DSL

In order to define the type of data returned, you must specify one or more additional query string variables or arguments. The form is name_of_field=type, where name_of_field will be the name used in the result and type is the type of data to mock the value with.

http://localhost:3000/?$num=3&author=name

# object
var data = getInstance( "[email protected]" )
    .mock(
        $num = 3,
        "author" = "name"
    );

This tells the service to return 3 objects with each containing an author field that has a type value of name. (More on types in a minute.) The result then would look something like this:

[
    {
        author: "Frank Smith"
    },
    {
        author: "Gary Stroz"
    },
    {
        author: "Lynn Padgett"
    }
]

Additional fields for the object model can just be appended to the URL or method call:

http://localhost:3000/?$num=3&author=name&gender=oneof:male:   female

# object
var data = getInstance( "[email protected]" )
    .mock(
        $num = 3,
        "author" = "name",
        "gender" = "oneOf:male:   female"
    );

Which gives...

[
    {
        author : "Lisa Padgett",
        gender : "male"
    },
    {
        author : "Roger Clapton",
        gender : "male"
    },
    {
        author : "Heather Degeneres",
        gender : "male"
    }
]

Nested Data

Since version v3.0.0, MockDataCFC supports the nesting of the field models to represent rich and complex JSON return structures. We currently support the following nested types:

  • array of objects - name = [ { ... } ]
  • array of values - name = [ { $type = "" } ]
  • object - name = { ... }

Let's imagine the following object graph:

Author
    Has Many Books
        Has Many Categories
    Has Keywords
    Has A Publisher

I can then use this mocking DSL to define it:

getInstance( "[email protected]" )
    .mock(

        fullName    = "name",
        description = "sentence",
        age         = "age",
        id          = "uuid",
        createdDate = "datetime",
        isActive	= "oneof:true: false",

        // one to many complex object definitions
        books = [
            {
                $num = "rand:1:      3",
                "id" = "uuid",
                "title" = "words:1:      5",
                "categories" = {
                    "$num"      = "2",
                    "id"        = "uuid",
                    "category"  = "words"
                }
            }
        ],

        // object definition
        publisher = {
            "id" 	= "uuid",
            "name" 	= "sentence"
        },

        // array of values
        keywords = [
            {
                "$num" 	= "rand:1:      10",
                "$type" = "words"
            }
        ]
    );

Nested Array of Values

To create nested array of values you will define the name of the property and then an array with a struct defining how many and of which type using the special keys: $num, $type

// array of values
keywords = [
    {
        "$num" 	= "rand:1:      10",
        "$type" = "words"
    }
]

Nested Array of Objects

To create nested array of objects you will define the name of the property and then an array with a struct defining how many and the definition of the object (Not there will be no type key):

// array of objects
books = [
    {
        $num = "rand:1:      3",
        "id" = "uuid",
        "title" = "words:1:      5",
        "categories" = {
            "$num"      = "2",
            "id"        = "uuid",
            "category"  = "words"
        }
    }
]

Nested Object

To create a nested object you will define the name of the property and then a struct defining it:

// object definition
publisher = {
    "id" 	= "uuid",
    "name" 	= "sentence"
}

Changelog

3.0.0

  • Compatibility : num arguments have been dropped and you must use $num as the identifier for how many items you like
  • Introduction of nested mocking. You can now declare nested mocks as structs and the mock data will nest accordingly:
getInstance( "[email protected]" )
	.mock(
		books=[{
			num=2,
			"id"="uuid",
			"title"="words:1: 5"
		}],
		fullName="name",
		description="sentence",
		age="age",
		id="uuid",
		createdDate="datetime"
	);

This will produce top level mock data with 2 books per record.

  • Nested Data for array of objects, array of values and simple objects
  • ACF Compatibilities
  • Updated readmes and syntax updates for modern engines
  • Upgraded to new ColdBox module Harness

2.4.0

  • Added auto-incrementing ID's FOR REAL this time

2.3.0

  • Added auto-incrementing ID's
  • Update on build control
  • Syntax Ortus Updates, addition of private methods
  • allow for use of rand or rnd for num generators
  • Add CORS support for ColdBox REST Module
  • Bug on isDefault() always returning true.
  • Added tests and automation

2.2.0

  • Made it a module as well for ColdBox apps.

2.0.0

  • Added support for words, sentences, uuid, bacon lorem, date and datetime
  • Added CommandBox Support
  • Added Documentation
  • Added ability to execute as a CFC instead of only via web service

1.0.0

Original by Ray Camden

 

 
$ box install mockdatacfc
No collaborators yet.
  • Oct 19 2016 08:52 AM
  • Oct 01 2018 03:41 PM
  • 720
  • 235
  • 223