Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create a Rest API fake in Groovy, using javascript npm modules (faker and json-server)
import org.grooscript.asts.GsNative
class Faker {
private _faker
@GsNative
private faker() {/*
if (!this._faker) {
this._faker = require('faker');
}
return this._faker;
*/}
@GsNative
private nodeExports(map) {/*
module.exports = function() {
return gs.toJavascript(map);
};
*/}
private resolveConfig(value, counter) {
if (value == 'inc') {
return counter + 1
} else {
def path = value.split('.')
if (path[0] == 'random') {
return new Random().nextInt(Integer.parseInt(path[1]))
} else {
return faker()[path[0]][path[1]]()
}
}
}
void exports(String name, int number, Map configuration) {
def list = []
println "Exporting ${number} ${name}."
number.times {
list << configuration.inject([:]) { map, conf ->
map[conf.key] = resolveConfig(conf.value, it)
map
}
}
nodeExports(["$name": list])
}
}
new Faker().exports('authors', 100, [
id: 'inc',
name: 'name.firstName',
city: 'address.city',
image: 'image.image',
birthDate: 'date.past',
age: 'random.99'
])
/*
Running json-server and going http://localhost:3000/authors
[
{
"id": 1,
"name": "Eva",
"city": "Port Casandramouth",
"image": "http://lorempixel.com/640/480/nature",
"birthDate": "2014-12-05T14:50:56.099Z",
"age": 63
},
{
"id": 2,
"name": "Jalen",
"city": "Friesenside",
"image": "http://lorempixel.com/640/480/animals",
"birthDate": "2015-04-04T09:56:54.155Z",
"age": 15
},
{
"id": 3,
"name": "Lelia",
"city": "Adamsborough",
"image": "http://lorempixel.com/640/480/nightlife",
"birthDate": "2014-10-28T23:12:59.849Z",
"age": 11
},
{
"id": 4,
"name": "Leta",
"city": "Albinamouth",
"image": "http://lorempixel.com/640/480/fashion",
"birthDate": "2014-12-08T14:17:23.575Z",
"age": 7
},
....
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment