Validate and return partial response from field, just like graphql, but without the black magic.


Validate and return partial response from field, just like graphql, but without the black magic.
Mainly for using with RESTful API gateway
Build with typescript. (Will not even think of making this kind of library without typing)
npm install --save-exact partial-responsifyNote: install the exact version or the patch version before the project pass 1.0, breaking change might happen in minor release pre 1.0
- simple csv with graphql like nested field
~~~ts
import { PartialResponsify, ResponseFormat } from "partial-responsify";
// ideally should be inside DI
const pr = new PartialResponsify();
// it is normally inside ctx.query for Koa
// default don't support whitespace or - or _
// (normally should be camelcase?)
const fields = "name,coords,author{name{first}}";
const responseFormat: ResponseFormat = {
fields: {
author: {
fields: {
name: {
fields: {
first: {
type: "string",
},
last: {
type: "string",
},
},
type: "object",
},
},
type: "object",
},
coords: {
items: {
items: {
type: "number",
},
type: "array",
},
type: "array",
},
license: {
type: "string",
},
name: {
type: "string",
},
},
type: "object",
};
// you can use this fieldsToParse to track the fields usage
const fieldsToParse = pr.parseFields(fields, responseFormat);
console.log(fieldsToParse);
// and then you perform some logic and got the result
const result = {
author: {
name: {
first: "Liam",
last: "Ng",
},
url: "https://www.leliam.com",
},
coords: [[13.37, 1.337], [0, 0]],
license: "MIT",
name: "partial-responsify",
};
const res = pr.parseResult
console.log(res);
/*
the result should be:
[ [ [], 'name' ],
[ [], 'coords' ],
[ [ 'author', 'name' ], 'first' ] ]
{ author: { name: { first: 'Liam' } },
coords: [ [ 13.37, 1.337 ], [ 0, 0 ] ],
name: 'partial-responsify' }
*/
~~~
- generate schema for use with swagger
~~~ts
import { ResponseFormat, SchemaGenerator } from "partial-responsify";
const sgen = new SchemaGenerator();
const responseFormat: ResponseFormat = {
items: {
fields: {
a: {
type: "number",
},
b: {
type: "string",
},
c: {
type: "integer",
},
d: {
format: "uuid",
type: "string",
},
e: {
fields: {
a: {
type: "number",
},
},
type: "object",
},
},
type: "object",
},
type: "array",
};
const result = sgen.generate(responseFormat);
console.log(result);
/*
{
items: {
properties: {
a: {
type: "number",
},
b: {
type: "string",
},
c: {
type: "integer",
},
d: {
format: "uuid",
type: "string",
},
e: {
properties: {
a: {
type: "number",
},
},
type: "object",
},
},
type: "object",
},
type: "array",
}
*/
~~~
- nested fields
- graphql way: const fields = "name,license,author{name{first,last},url}";
- generate example string to get full response based on ResponseBody with FieldsExampleGenerator
const fields = "name,license,author(name(first,last),url)";