npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-mocker

v0.0.3

Published

A simple Mockup Server for REST services that can generate fake data based on simple JSON templates.

Downloads

5

Readme

#ExpressMocker

WIP Alpha 0.0.2 Not full tested. Not for production.

A small FAKE REST web server for your daily development.

Features

  • Small

  • Configured via json or by an included Dashboard

  • Uses ExpressJS

  • Define an endpoint and return JSON data based on a template object

  • FakeData generator to use in templates

  • Simple NodeJS implemented localStorage instance to store things

  • Custom methods can be defined in templates

  • Can generate SVG imagen on the fly

  • Custom methods can use "Injected" arguments

    • $request // $request object containing GET/POST data
    • $localStorage // localStorage "one file" node implementation
    • $console // debug to node console from the template
    • $helper // access DataFackerHelper methods
    • $utils // access DataFackerUtils methods

##Installation

You need nodejs installed and running in your system.

Clone locally the repository.

Go to your local source folder an type:

	sudo npm install -g

This will install "express-mocker" globally.

##Command Line Usage

###Installing First we need to initialize our express-mocker instance in some dir. To initialize it in any wanted directory type:

express-mocker --install
express-mocker --forceInstall // Overwrites your files!!!

This will create a subdir named "express-mocker" with some config files.

###Running

In a dir containing the express-mocker dir type:

express-mocker

This will run express-mocker with the default config.json port and verbose options.

Now you can go to your browser and type this address to acces the dashboard.

http://127.0.0.1:7878/express-mocker

You can also use this command line flags:

express-mocker --port <port> // sets the port
express-mocker --quiet	   // force run in quiet mode

Force exit ;-)

In the case you need to force close the port you can use this command:

express-mocker --die <port> // closes the port

Template system

Basic Templating

ExpressMocker uses a simple template system defined by a javascript object:

var jsonmocker =
{
	"static": "value", // static value
	"fakeName": "{{firstName}}", // run firstName helper
	"staticArray": [10, 20], // static array
	"dynamicArray": [
		"$repeat(2)", // next item in array will be repeated 2 times
		{
			"name": "{{firstName}} {{lastName}}",
			"age": "{{random(80)}}"
		}
	]
}

This will output something like this:

{
	"static": "value",
	"fakeName": "Shea",
	"staticArray": [ 10,20 ],
	"dynamicArray": [
    	{
        	"name": "Baron Green",
        	"age": "69"
    	},
    	{
        	"name": "Abdullah Gibson",
    	    "age": "48"
	    }
    ]
}

Using GET/POST vars

var jsonmocker = 
{
	"property":"{{var-name}}"
}

So for:

/test/:myVar/:mySecondVar

We can the take the values as:

var jsonmocker = 
{
	 "request_myVar":"{{myVar}}"
	,"request_mySecondVar":"{{mySecondVar}}"
}

Custom template methods

You can define custom methods for use in your templates.

var jsonmocker = 
{
	"hello":"{{customMethod}}",
	"hello25":"{{customMethodWithParams(25)}}",
	"customMethod": function(){
		return "World!!"
	},
	"customMethodWithParams":function(numberOfWorlds){
		return "World "+numberOfWorlds+" !!"
	}
}
	

Output

{
	"hello":"World!!",
	"hello25":"World 25 !!"
}		

Possible Injections in your functions

ExpressMocker uses a simple Injection system with this injections available:

  • $request // $request object containing GET/POST data
  • $localStorage // localStorage "one file" node implementation
  • $console // debug to node console from the template
  • $helper // access DataFackerHelper methods
  • $utils // access DataFackerUtils methods

Using it in your custom methods is simple as:

var jsonmocker =
{
	// REMEMBER!! You must put FIRST the non Injected params
	customTelephone:function( prefix, $utils )
	{
		return $utils.replacePattern( prefix+'.4##.##.##.##');
	},
	"phone":"{{customTelephone('+33')}}"
}	

Output

{
	"phone":"+33.456.78.90"
}	

Storing data

A special key $preprocessRequest is reserved to indicate the template that request preprocesing must be done.

Here is where we can use the $localStorage injection most time.

A simple fake GET user registration can be done via:

For this route:

/user/register/:user/:password

var jsonmocker =
{
	"$preprocessRequest":function( $localStorate, $request )
	{
		$localStorate.setItem
		(
			'singleUserStore',
			JSON.stringify
			(
				{
					user:$request.params('user),
					password:$request.params('password)
				}
			)
		);
	},
	"code":100		
}

Calling:

/user/register/test/1234

Will generate a singleUserStore key with a JSON representation of the user object.

Direct raw base64 Output

A special key $content key "is reserved to indicate that the value of this key must be processed as a base64 output stream.

var jsonmocker =
{
	"$content":"data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
}

This will ouput a 1pix gif image ;-) or call it with the provided image function:

var jsonmocker =
{
	"$content":"{{image(320,480)}}"
}

API Reference

|Injectors|$helper|$utils| |-----|----|----| |$helper |firstName |slug(str) |$utils |lastName |shuffle(array) |$scope |company |titleCase(str) |$localStorage |email |replacePattern(pattern) |$request |bool |randomElement(elements) |$console |image(width,height) |randomNumber(range) |$helper |guid |randomNumberRange(start,end) | |loremWords | |lorem

$scope

The $scope object lets you access your other template methods.

{
	hello:function(){ return 'Hello' },
	world:function(){ return 'world!!' },
	helloWorld:function($scope){
		return $scope.hello()+$scope.world();
	}
	"output":"{{helloWorld}}"
}

$localStorage

Use it as it was the client localStorage but with disk storage.

See more at the project page: https://github.com/coolaj86/node-dom-storage

$request

Provides access to the query params and the processed body headers.

#####params( id:string ):string;

Returns the request query parameter specified by id. 

#####body( id:string ):any;

Returns the request body object specified by id. 

$console

Provides a unified form ( with quiet mode ) to log messages to the console.

Supported methods:

  • log(…rest)
  • info(…rest)
  • error(…rest)
  • success(…rest)

$helper

#####firstName

{{firstName}} 
Returns a random First Name. 

#####lastName

{{lastName} 

Returns a random Last Name.

#####company

{{company}}
Returns a random Company name.

#####email

{{email}}
Returns a random generated email.

#####bool

{{bool}}
Returns a random boolean value.
	

#####image(width,height)

{{image(width,height)}}
Returns a random base64 encoded svg image.

#####guid

{{guid}}
Returns a random Globally unique identifier.

#####loremWords(number)

{{loremWords(number)}}
Returns a random number of loremipsum words.

#####lorem( paragraphs,html=false,sentenceWords=(15-45) )

{{lorem(5)}}
Returns a loremipsum string composed of n paragraphs.

{{lorem(5,true)}}
If html is true it will add <p> tags for each paragraph.

{{lorem(5,true,15)}}
Determine words per sentence. Default is a random value 15-45

$utils

#####slug(str:string):string

{{slug('some long texy')}}
Returns a slugged version of str.

#####shuffle(array:any[]):any[]

{{shuffle(array)}}
Returns a randomided version of the provided array.

#####titleCase(str:string):string

{{titleCase(str)}}
Returns a titleCase representation of str.

#####replacePattern(pattern):string

{{replacePattern('####-UUUU-LLLL')}}
Processes the provided pattern replacing:

# by a number.
U by a uppercase letter.
L by a lowercase letter.

#####randomElement(elements:any[]):any

{{randomElement([10,\"demo\",true])}}
Returns a random element from the provided array.

#####randomNumber(max)

{{randomNumber(25)}}
Returns a random number between 0 and max;

#####randomNumberRange(start,end)

{{randomNumberRange(5,10)}}
Returns a random number between start and end;