1.0.0 • Published 6 years ago

cruddie-mock v1.0.0

Weekly downloads
3
License
MIT
Repository
github
Last release
6 years ago

Cruddie Mock

Dead simple API mocking tool. Supply a folder full of json files describing your models, get a working REST API with CRUD methods for mock data. Cruddie Mock was built with simplicity in mind, so it should set you up for success.

For an example server, check out the live demo

Quickstart Guide

  1. Install cruddie-mock globally: npm install -g cruddie-mock
  2. Create your models using json objects in your project. (See examples folder)
  3. From the command line, open the folder your json files are in
  4. Start the server: cruddie-mock
  5. Open http://localhost:3009/

Command Line Usage

Usage: cruddie-mock [options] [directory path]

[directory path] should be a directory with json files describing your models. If
omitted, the current working directory will be used instead. Regular require-style
javascript (.js) files will also work - export your model.

Options

cruddie-mock provides a number of command-line options to make configuring it simple for most use cases. All options are also available as environment variables. If both are provided, command line options override environment variables.

ArgumentShort ArgEnvironment VarDescription
--port-pPORTPort to run process on (default 3009)
--result-count-rRESULT_COUNTNumber of results to put in an API by default. (default 50)
--hostn/aHOSTHost to bind to. (Default 0.0.0.0, or all interfaces)
--no-corsn/aNO_CORSDisable Cross-Origin Resource Sharing
--no-gzipn/aNO_GZIPDisable ZIP compression in responses
--swagger-urln/aSWAGGER_URLDomain/port used for API. Use if hosting on a domain instead of localhost.
--read-onlyn/aREAD_ONLYOnly allow GET requests
--versionvn/aPrint version and exit

Model Format

Models are simply json files with a special syntax for anything you want to be randomized. A plain json file will also work. For some live examples, check the examples folder.

Built-in variables

KeyExampleDescription
{{id}}1Auto-incrementing ID. Unique per model
{{example}}exampleThe word example. Used for documentation.
{{foreign_id(model_name}}5A valid id that links to the model named in parenthesis

Faker-powered Variables

Address

KeyExampleDescription
{{address.zipCode}}86966zipCode object.
{{address.city}}Gradyburycity object.
{{address.cityPrefix}}LakecityPrefix object.
{{address.citySuffix}}boroughcitySuffix object.
{{address.streetName}}Bridget VillagestreetName object.
{{address.streetAddress}}411 Dare CanyonstreetAddress object.
{{address.streetSuffix}}KeystreetSuffix object.
{{address.streetPrefix}}cstreetPrefix object.
{{address.secondaryAddress}}Suite 116secondaryAddress object.
{{address.county}}Avoncounty object.
{{address.country}}Tokelaucountry object.
{{address.countryCode}}CIcountryCode object.
{{address.state}}Alabamastate object.
{{address.stateAbbr}}MSstateAbbr object.
{{address.latitude}}-51.6628latitude object.
{{address.longitude}}126.4665longitude object.

Commerce

KeyExampleDescription
{{commerce.color}}orangecolor object.
{{commerce.department}}Electronicsdepartment object.
{{commerce.productName}}Fantastic Granite GlovesproductName object.
{{commerce.price}}151.00price object.
{{commerce.productAdjective}}SleekproductAdjective object.
{{commerce.productMaterial}}FreshproductMaterial object.
{{commerce.product}}Ballproduct object.

Company

KeyExampleDescription
{{company.suffixes}}Inc,and Sons,LLC,Groupsuffixes object.
{{company.companyName}}Rosenbaum InccompanyName object.
{{company.companySuffix}}GroupcompanySuffix object.
{{company.catchPhrase}}Optional cohesive approachcatchPhrase object.
{{company.bs}}next-generation whiteboard vortalsbs object.
{{company.catchPhraseAdjective}}PolarisedcatchPhraseAdjective object.
{{company.catchPhraseDescriptor}}context-sensitivecatchPhraseDescriptor object.
{{company.catchPhraseNoun}}forecastcatchPhraseNoun object.
{{company.bsAdjective}}end-to-endbsAdjective object.
{{company.bsBuzz}}incubatebsBuzz object.
{{company.bsNoun}}e-commercebsNoun object.

Database

KeyExampleDescription
{{database.column}}namecolumn object.
{{database.type}}decimaltype object.
{{database.collation}}cp1250_bincollation object.
{{database.engine}}MEMORYengine object.

Date

KeyExampleDescription
{{date.past}}Fri Aug 04 2017 12:01:40 GMT-0400 (Eastern Daylight Time)past object.
{{date.future}}Mon Jan 01 2018 19:15:34 GMT-0500 (Eastern Standard Time)future object.
{{date.recent}}Fri Sep 08 2017 18:23:21 GMT-0400 (Eastern Daylight Time)recent object.
{{date.month}}Marchmonth object.
{{date.weekday}}Sundayweekday object.

Finance

KeyExampleDescription
{{finance.account}}81777179account object.
{{finance.accountName}}Credit Card AccountaccountName object.
{{finance.mask}}0926mask object.
{{finance.amount}}275.73amount object.
{{finance.transactionType}}deposittransactionType object.
{{finance.currencyCode}}VEFcurrencyCode object.
{{finance.currencyName}}Zimbabwe DollarcurrencyName object.
{{finance.currencySymbol}}£currencySymbol object.
{{finance.bitcoinAddress}}1632O02TB7R9R2CXJQMWVMBL23K4bitcoinAddress object.
{{finance.iban}}LV51LLBW360H89FZ74H3Iiban object.
{{finance.bic}}FFVEHRE1bic object.

Hacker

KeyExampleDescription
{{hacker.abbreviation}}SASabbreviation object.
{{hacker.adjective}}1080padjective object.
{{hacker.noun}}bandwidthnoun object.
{{hacker.verb}}back upverb object.
{{hacker.ingverb}}hackingingverb object.
{{hacker.phrase}}You can't copy the microchip without navigating the open-source GB program!phrase object.

Image

KeyExampleDescription
{{image.image}}http://lorempixel.com/640/480/abstractimage object.
{{image.avatar}}https://s3.amazonaws.com/uifaces/faces/twitter/charliegann/128.jpgavatar object.
{{image.imageUrl}}http://lorempixel.com/640/480imageUrl object.
{{image.abstract}}http://lorempixel.com/640/480/abstractabstract object.
{{image.animals}}http://lorempixel.com/640/480/animalsanimals object.
{{image.business}}http://lorempixel.com/640/480/businessbusiness object.
{{image.cats}}http://lorempixel.com/640/480/catscats object.
{{image.city}}http://lorempixel.com/640/480/citycity object.
{{image.food}}http://lorempixel.com/640/480/foodfood object.
{{image.nightlife}}http://lorempixel.com/640/480/nightlifenightlife object.
{{image.fashion}}http://lorempixel.com/640/480/fashionfashion object.
{{image.people}}http://lorempixel.com/640/480/peoplepeople object.
{{image.nature}}http://lorempixel.com/640/480/naturenature object.
{{image.sports}}http://lorempixel.com/640/480/sportssports object.
{{image.technics}}http://lorempixel.com/640/480/technicstechnics object.
{{image.transport}}http://lorempixel.com/640/480/transporttransport object.
{{image.dataUri}}Data URI goes hereA Data URI object.

Internet

KeyExampleDescription
{{internet.avatar}}https://s3.amazonaws.com/uifaces/faces/twitter/j04ntoh/128.jpgavatar object.
{{internet.email}}Thurman_Howell@yahoo.comemail object.
{{internet.exampleEmail}}Derrick.Blick@example.comexampleEmail object.
{{internet.userName}}Marge_HettingeruserName object.
{{internet.protocol}}httpsprotocol object.
{{internet.url}}http://genoveva.neturl object.
{{internet.domainName}}birdie.comdomainName object.
{{internet.domainSuffix}}bizdomainSuffix object.
{{internet.domainWord}}lacydomainWord object.
{{internet.ip}}164.123.119.107ip object.
{{internet.ipv6}}c58a:23c6:39f8:ad74:2e72:28ac:8f96:3b3fipv6 object.
{{internet.userAgent}}Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/7.0; .NET CLR 2.0.57178.2)userAgent object.
{{internet.color}}#5b2c38color object.
{{internet.mac}}48:4e:65:ff:a6:7bmac object.
{{internet.password}}aqb0BbU44XSkgbVpassword object.

Lorem

KeyExampleDescription
{{lorem.word}}quiword object.
{{lorem.words}}accusantium earum quiwords object.
{{lorem.sentence}}Quo quas omnis assumenda libero.sentence object.
{{lorem.slug}}saepe-est-suntslug object.
{{lorem.sentences}}Lorem ipsum...A few sentences.
{{lorem.paragraph}}Lorem ipsum...A paragraph.
{{lorem.paragraphs}}Lorem ipsum...A few paragraphs.
{{lorem.text}}Lorem ipsum...Lorem ipsum text with newline characters.
{{lorem.lines}}Lorem ipsum...Lorem ipsum text with newline characters.

Name

KeyExampleDescription
{{name.firstName}}FletcherfirstName object.
{{name.lastName}}BlicklastName object.
{{name.findName}}Hiram HoegerfindName object.
{{name.jobTitle}}Dynamic Accountability AssistantjobTitle object.
{{name.prefix}}Dr.prefix object.
{{name.suffix}}Sr.suffix object.
{{name.title}}Senior Metrics Plannertitle object.
{{name.jobDescriptor}}DynamicjobDescriptor object.
{{name.jobArea}}WebjobArea object.
{{name.jobType}}TechnicianjobType object.

Phone

KeyExampleDescription
{{phone.phoneNumber}}681.712.3445 x781phoneNumber object.
{{phone.phoneNumberFormat}}273-435-5932phoneNumberFormat object.
{{phone.phoneFormats}}(###) ###-#### x###phoneFormats object.

Random

KeyExampleDescription
{{random.number}}30148number object.
{{random.arrayElement}}carrayElement object.
{{random.objectElement}}barobjectElement object.
{{random.uuid}}b0223f3a-48af-4aaa-aecc-eda906c19304uuid object.
{{random.boolean}}falseboolean object.
{{random.word}}Credit Card Accountword object.
{{random.words}}Avon olive Fishwords object.
{{random.image}}http://lorempixel.com/640/480/foodimage object.
{{random.locale}}kolocale object.
{{random.alphaNumeric}}nalphaNumeric object.

System

KeyExampleDescription
{{system.fileName}}next_generation_best_of_breed.atcfileName object.
{{system.commonFileName}}tangible_central_tools.mpgacommonFileName object.
{{system.mimeType}}application/cals-1840mimeType object.
{{system.commonFileType}}videocommonFileType object.
{{system.commonFileExt}}wavcommonFileExt object.
{{system.fileType}}imagefileType object.
{{system.fileExt}}csmlfileExt object.
{{system.semver}}9.5.3semver object.

Linking models together

If you define multiple models, the foreign_id field will let you link them together, similar to a join in mysql. cruddie-mock will look at the other model you reference, and pick a random id to link it to. Here's what it looks like, with an excerpt from upload.json in the application example:

{
  "name": "{{system.fileName}}",
  "userId": "{{foreign_id(user)}}"
}

As long as you have a user model, this will find a valid user id to put into this field. This by itself is kinda useful, but you can also use the API to fetch all uploads owned by a user, or fetch the user object with your upload. Run the application demo and look at the swagger documentation to see how.

Meta information

Models can have a special _meta field, which can customize settings about how cruddie-mock handles the model.

Right now, the only option available is count, which will change the number of results generated, instead of using the default. There is an example in the uploads model in the applications example.

Node API?

The module doesn't have a nodejs API, at least not yet. This is a planned feature, but I have no estimate for when it might be implemented.

Contributing

The short answer is, send a PR! There are plenty of guides online to help you do this if you're new to it. I don't have any hard-and-fast rules - just please try to write tests if you are adding complex logic. I'm sure we can figure out a way to get your changes in.

Publishing new versions

This is mainly a note for myself, and any other contributors that might come along. Publishing is currently a manual process. Run the following commands, filling in details as needed.

npm version [patch|minor|major] -m "This is what we did"
git push && git push --tags

After this, please fill out the release notes on github. (Yes, manually. Sorry!)

A few words on testing...

This is the first personal project I've ever put effort into writing tests for. They probably are not super great, but my hope is that they will give contributors some confidence in their changes.

That said, I am not a firm believer in 100% test coverage, nor in complicating code to write better unit tests.

Don't let tests hold you up from submitting a PR! Whether you feel like some are missing, or you have tests failing for no reason - just note it in the PR and we'll get things working. My tests may need to be rewritten, or scrapped completely.

Modules we use and love

  • json-server: Great little script that creates express-friendly CRUD endpoints for a given object or json file.
  • faker.js: Has a ton of methods to create believable fake data.
  • swagger-ui: Functional UI around the OpenAPI specification, makes testing APIs simple and intuitive.

License

This software is released under the MIT license, detailed in the LICENSE file. Note that included modules such as swagger-ui, faker.js, and json-server may use separate licenses, such as the Apache license.