const seeded = Fiona(2983938)

Examples

Mock API

Mocking `fetch` with Fetch Pretender

Assuming some kind of setup code loading Fetch Pretender

<script src="https://cdn.rawgit.com/billymoon/fetch-pretender/master/dist/pretender.js"></script>

You can define a mock server like this...

const pretender = new Pretender()

const modelMock = seed => Fiona(seed).object({
  fullname: seeded => seeded.fullname(),
  color: seeded => seeded.oneOf(['red', 'yellow', 'blue']),
  age: seeded => seeded.number({ max: 100 })
})

pretender.get('/user/:id', request => [
  200,
  { 'Content-Type': 'application/json' },
  JSON.stringify(modelMock(request.params.id))
])    

Calls to fetch on specified routes will now be patched to return mock results generated by Fiona.

// input

fetch('/user/2983938').then(r => r.text()).then(console.log)
// output

{"fullname":"Mr Elliot Alex Thomas Wilson","color":"yellow","age":1}

Express Mock Server

This example assumes you have a project with dependencies added for Fiona, express and express-http-proxy and that you have a development server running on port 3000 serving your web app.

Define an express proxy server and run with nodejs - e.g. save the snippet as `server.js` and run `node server`

// require dependencies
const Fiona = require('fiona')
const proxy = require('express-http-proxy')
const express = require('express')

// define express server
const app = express()

// define Fiona generated data handler for user api
app.use('/api/user/:id', (req, res) => {
  res.end(Fiona(req.params.id).chain({
    fullname: Fiona.Fullname,
    age: Fiona.Number({ max: 100 })
  }).json())
})

// proxy other requests to main server
app.use('/', proxy('http://localhost:3000'))

// listen on an available port
app.listen(3001, () => console.log(`mocking '/api/user/:id' and proxying 3000 to 3001`))

The proxy server (running on http://localhost:3001) will forwarding traffic to your development server (running on http://localhost:3000) except api calls to /api/user/:id which will return generated data as json.

From the proxied web page, you can now make requests to the user api along the lines of...

// input

fetch('/api/user/2983938').then(r => r.json()).then(console.log)
// output

{"fullname":"Mr Elliot Alex Thomas Wilson","age":1}
... or with curl ...
$ curl http://localhost:3001/api/user/2983938