bbj/documentation/docs/validation.md

96 lines
2.6 KiB
Markdown
Raw Normal View History

2017-05-04 02:35:47 +00:00
## Implementing good sanity checks in your client.
2017-04-08 07:27:05 +00:00
The server has an endpoint called `db_validate`. What this does is take
2017-05-04 02:35:47 +00:00
a `key` and a `value` argument, and compares `value` to a set of rules specified by
`key`. This is the same function used internally by the database to check
2017-04-05 03:10:48 +00:00
values before committing them to the database. By default it returns a
descriptive object under `data`, but you can specify the key/value pair
`"error": True` to get a standard error response back. A standard call
2017-04-08 07:27:05 +00:00
to `db_validate` will look like this.
2017-04-05 03:10:48 +00:00
```
{
"key": "title",
"value": "this title\nis bad \nbecause it contains \nnewlines"
}
```
and the server will respond like this when the input should be corrected.
```
{
"data": {
"bool": False,
"description": "Titles cannot contain whitespace characters besides spaces."
},
"error": False,
"usermap": {}
}
```
if everything is okay, the data object will look like this instead.
```
"data": {
"bool": True,
"description": null
},
```
Alternatively, you can supply `"error": True` in the request.
```
{
"error": True,
"key": "title",
"value": "this title\nis bad \nbecause it contains \nnewlines"
}
// and you get...
{
"data": null,
"usermap": {},
"error": {
"code": 4,
"description": "Titles cannot contain whitespace characters besides spaces."
}
}
```
The following keys are currently available.
* "user_name"
* "auth_hash"
* "quip"
* "bio"
* "title"
* "body"
* "color"
The descriptions returned are friendly, descriptive, and should be shown
directly to users
By using this endpoint, you will never have to validate values in your
own code before sending them to the server. This means you can do things
like implement an interactive prompt which will not allow the user to
submit it unless the value is correct.
This is used in the elisp client when registering users and for the thread
title prompt which is shown before opening a composure window. The reason
for rejection is displayed clearly to the user and input window is restored.
2017-05-04 02:35:47 +00:00
```lisp
2017-04-05 03:10:48 +00:00
(defun bbj-sane-value (prompt key)
"Opens an input loop with the user, where the response is
passed to the server to check it for validity before the
user is allowed to continue. Will recurse until the input
is valid, then it is returned."
(let* ((value (read-from-minibuffer prompt))
2017-05-04 02:35:47 +00:00
(response (bbj-request! 'db_validate 'value value 'key key)))
2017-04-05 03:10:48 +00:00
(if (alist-get 'bool response)
2017-05-04 02:35:47 +00:00
value ;; return the user's input back to the caller
2017-04-05 03:10:48 +00:00
(message (alist-get 'description response))
(sit-for 2)
(bbj-sane-value prompt key))))
```