You're reading Mocko v1 (legacy) documentation. Mocko v2 is the current version. View the v2 docs.

Persistence

Mocko allows you to use Flags: values that persist between requests, or even between restarts when Redis is enabled. Redis is on by default in the complete stack and off by default in standalone mode (falls back to in-memory).

Getting started

Create a PUT /message/{message} that saves a flag and a GET /message that returns it:

mock "PUT /message/{message}" {
body = <<EOF
{{! Setting the flag 'msg' to the value of the 'message' param }}
{{setFlag 'msg' request.params.message}}
EOF
}

mock "GET /message" {
body = <<EOF
{{getFlag 'msg'}}
EOF
}

Set the message:

$ curl -X PUT http://localhost:8080/message/potato

Get the message back:

$ curl http://localhost:8080/message
potato

More helpers

You can also check whether a flag exists and delete it. Here is the previous example extended with hasFlag and delFlag:

mock "PUT /message/{message}" {
body = "{{setFlag 'msg' request.params.message}}"
}

mock "GET /message" {
body = <<EOF
{{#hasFlag 'msg'}}
{{getFlag 'msg'}}
{{else}}
{{setStatus 404}}
No message is set
{{/hasFlag}}
EOF
}

mock "DELETE /message" {
body = "{{delFlag 'msg'}}"
}

Delete the flag:

$ curl -X DELETE http://localhost:8080/message

Now GET returns 404:

$ curl -D - http://localhost:8080/message

HTTP/1.1 404 Not Found
No message is set

Dynamic flags

Use request data to build a flag's name so you can store multiple resources. The : separator renders as folder groups in the UI:

mock "POST /users" {
headers {
Content-Type = "application/json"
}
body = <<EOF
{{set 'id' (uuid)}}
{{setFlag (append 'users:' (get 'id') ':name') request.body.name}}
{{setFlag (append 'users:' (get 'id') ':age') request.body.age}}
{
"id": "{{get 'id'}}"
}
EOF
}

mock "GET /users/{id}" {
body = <<EOF
{{#hasFlag (append 'users:' request.params.id ':name')}}
Hello! My name is {{getFlag (append 'users:' request.params.id ':name')}}
and I'm {{getFlag (append 'users:' request.params.id ':age')}} years old
{{else}}
{{setStatus 404}}
{{/hasFlag}}
EOF
}

Create a user:

$ curl -X POST http://localhost:8080/users \
  -d '{"name": "George", "age": 95}' \
  -H 'Content-Type: application/json'
{
  "id": "8dfad38d-56e9-4210-8dfa-1c8f9da213f2"
}

Retrieve by ID:

$ curl http://localhost:8080/users/8dfad38d-56e9-4210-8dfa-1c8f9da213f2
Hello! My name is George
and I'm 95 years old

Each user gets a unique UUID-based key, so creating a new user never overwrites an existing one.