feat: bru lang - support body default as json

This commit is contained in:
Anoop M D 2023-02-06 01:27:08 +05:30
parent a0cb53445f
commit 3e563ea126
2 changed files with 89 additions and 2 deletions

View File

@ -25,7 +25,7 @@ const {
*/
const grammar = ohm.grammar(`Bru {
BruFile = (meta | http | query | headers | bodies | varsandassert | script | tests | docs)*
bodies = bodyjson | bodytext | bodyxml | bodygraphql | bodygraphqlvars | bodyforms
bodies = bodyjson | bodytext | bodyxml | bodygraphql | bodygraphqlvars | bodyforms | body
bodyforms = bodyformurlencoded | bodymultipart
nl = "\\r"? "\\n"
@ -67,6 +67,7 @@ const grammar = ohm.grammar(`Bru {
varslocal = "vars:local" dictionary
assert = "assert" dictionary
body = "body" st* "{" nl* textblock tagend
bodyjson = "body:json" st* "{" nl* textblock tagend
bodytext = "body:text" st* "{" nl* textblock tagend
bodyxml = "body:xml" st* "{" nl* textblock tagend
@ -165,8 +166,18 @@ const sem = grammar.createSemantics().addAttribute('ast', {
return elements.map(e => e.ast);
},
meta(_1, dictionary) {
let meta = mapPairListToKeyValPair(dictionary.ast);
if(!meta.seq) {
meta.seq = 1;
}
if(!meta.type) {
meta.type = 'http';
}
return {
meta: mapPairListToKeyValPair(dictionary.ast)
meta
};
},
get(_1, dictionary) {
@ -249,6 +260,16 @@ const sem = grammar.createSemantics().addAttribute('ast', {
}
};
},
body(_1, _2, _3, _4, textblock, _5) {
return {
http: {
body: 'json'
},
body: {
json: outdentString(textblock.sourceString)
}
};
},
bodyjson(_1, _2, _3, _4, textblock, _5) {
return {
body: {

View File

@ -0,0 +1,66 @@
const bruToJson = require("../src/bruToJson");
describe("defaults", () => {
it("should parse the default type and seq", () => {
const input = `
meta {
name: Create user
}
post {
url: /users
}
`;
const expected = {
"meta": {
"name": "Create user",
"seq": 1,
"type": "http"
},
"http": {
"method": "post",
"url": "/users"
}
};
const output = bruToJson(input);
expect(output).toEqual(expected);
});
it("should parse the default body mode as json if the body is found", () => {
const input = `
meta {
name: Create user
}
post {
url: /users
}
body {
{
name: John
age: 30
}
}
`;
const expected = {
"meta": {
"name": "Create user",
"seq": 1,
"type": "http"
},
"http": {
"method": "post",
"url": "/users",
"body": "json"
},
"body": {
"json": "{\n name: John\n age: 30\n}"
}
};
const output = bruToJson(input);
expect(output).toEqual(expected);
});
});