Skip to content

Instantly share code, notes, and snippets.

@legrego
Created November 25, 2019 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save legrego/4109d531b3635c741c7b36405a30f109 to your computer and use it in GitHub Desktop.
Save legrego/4109d531b3635c741c7b36405a30f109 to your computer and use it in GitHub Desktop.
Using @kbn/config-schema to validate Legacy Platform routes
import { schema } from '@kbn/config-schema';
function defineMyRoute(server) {
const routeValidationSchema = schema.object({
foo: schema.string(),
bar: schema.maybe(schema.number({ min: 2, max: 200 })),
baz: schema.boolean()
});
server.route({
method: 'POST',
path: '/api/my_app/my_app_route',
options: {
validate: {
payload: function(payloadBody) {
return routeValidationSchema.validate(payloadBody);
}
}
},
handler(request, response) {
doSomeWork(request);
}
});
}
@legrego
Copy link
Author

legrego commented Nov 25, 2019

Example output for failed request:

elastic-mbp:8.0.0 larry$ curl https://localhost:5601/foo/api/security/v1/me -u elastic:changeme -X POST -H kbn-xsrf:true -H content-type:application/json -d'{"foo": 12}'
{"statusCode":400,"error":"Bad Request","message":"[foo]: expected value of type [string] but got [number]","validation":{"source":"payload","keys":[]}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment