Created
November 21, 2017 19:10
-
-
Save collin/b8d184753adec77bec3c3a76bc07007a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express') | |
const morgan = require('morgan') | |
const Chance = require('chance') | |
const app = express() | |
app.use(morgan('dev')) | |
const chance = new Chance() | |
Chance.prototype['3d6'] = function () { | |
return this.d6() + this.d6() + this.d6() | |
} | |
Chance.prototype.articleBody = function () { | |
return [ | |
'<p>' + this.paragraph(), | |
this.paragraph(), | |
this.paragraph(), | |
this.paragraph(), | |
this.paragraph(), | |
this.paragraph() + '</p>' | |
].join('</p>\n<p>') | |
} | |
Chance.prototype['16x9'] = function () { | |
return 'http://placekitten.com/g/800/450' | |
} | |
Chance.prototype['1x1'] = function () { | |
return 'http://placekitten.com/g/400/400' | |
} | |
Chance.prototype.profile = function () { | |
return buildObject( | |
'age', 'name', 'twitter', 'email', { | |
avatar: '1x1', | |
strength: '3d6', | |
constitution: '3d6', | |
dexterity: '3d6', | |
intelligence: '3d6', | |
wisdom: '3d6', | |
charisma: '3d6', | |
} | |
) | |
} | |
Chance.prototype.article = function () { | |
return buildObject( | |
{ | |
headline: 'sentence', | |
author: 'profile', | |
body: 'articleBody', | |
image: '16x9', | |
} | |
) | |
} | |
function buildObject (...keys) { | |
const object = {} | |
keys.forEach(key => { | |
if (typeof key === 'object') { | |
Object.entries(key).forEach(([_key, value]) => { | |
try { | |
object[_key] = chance[value]() | |
} | |
catch (error) { | |
object[_key] = `Don't know how to make a \`${value}\`` | |
} | |
}) | |
} | |
else { | |
try { | |
object[key] = chance[key]() | |
} | |
catch (error) { | |
object[key] = `Don't know how to make a \`${key}\`` | |
} | |
} | |
}) | |
return object | |
} | |
const methods = { | |
} | |
app.get('/:method', (req, res, next) => { | |
const { seed, method } = req.params | |
if (chance[method]) { | |
res.send(200, chance[method](req.query)) | |
} | |
else { | |
next() | |
} | |
}) | |
app.get('/:method/:count', (req, res, next) => { | |
const { seed, method } = req.params | |
if (chance[method]) { | |
const items = [] | |
const count = parseInt(req.params.count, 10) | |
for (let i = 0; i < count; i++) { | |
items.push(chance[method](req.query)) | |
} | |
res.send(200, items) | |
} | |
else { | |
next() | |
} | |
}) | |
app.listen(3333, () => { | |
console.log('Givin\' it a chance on port 3333') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment