Skip to content
10 changes: 9 additions & 1 deletion lib/RestClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,16 @@ export class RestClient {

let url: string = util.getUrl(resource, this._baseUrl);
let headers: ifm.IHeaders = this._headersFromOptions(options, true);
let data: string;

if (headers["Content-Type"].includes("application/json")) {
data = JSON.stringify(resources, null, 2);
}

else {
data = resources;
}

let data: string = JSON.stringify(resources, null, 2);
let res: httpm.HttpClientResponse = await this.client.post(url, data, headers);
return this.processResponse<T>(res, options);
}
Expand Down
16 changes: 15 additions & 1 deletion test/tests/resttests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ export interface HttpBinData {
url: string;
data: any;
json: any;
args?: any
args?: any;
form: any;
}

describe('Rest Tests', function () {
Expand Down Expand Up @@ -93,6 +94,19 @@ describe('Rest Tests', function () {
assert(restRes.result && restRes.result.json.name === 'foo');
});

it('creates a resource with a url encoded body', async () => {
let options: restm.IRequestOptions = {
additionalHeaders: {
'Content-Type': 'application/x-www-form-urlencoded',
}
};
let res: string = 'body=url%20encoded%20body';
let restRes: restm.IRestResponse<HttpBinData> = await _restBin.create<HttpBinData>('post', res, options);
assert(restRes.statusCode == 200, "statusCode should be 200");
assert(restRes.result && restRes.result.url === 'https://httpbin.org/post');
assert(restRes.result && restRes.result.form.body === 'url encoded body');
});

it('creates a resource with a baseUrl', async() => {
let res: any = { name: 'foo' };
let restRes: restm.IRestResponse<HttpBinData> = await _restBin.create<HttpBinData>('post', res);
Expand Down
23 changes: 23 additions & 0 deletions test/units/resttests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,29 @@ describe('Rest Tests', function () {
assert(restRes.result && restRes.result.json === 'foo');
});

it('creates a resource with a url encoded body', async () => {
nock('http://microsoft.com')
.post('/')
.reply(200, function (uri, requestBody) {
let body = decodeURI(requestBody);
return {
url: 'http://microsoft.com/post',
data: body,
json: null
};
});
let options: restm.IRequestOptions = {
additionalHeaders: {
'Content-Type': 'application/x-www-form-urlencoded',
}
};
let res: string = 'url%20encoded%20body';
let restRes: restm.IRestResponse<HttpData> = await _rest.create<HttpData>('http://microsoft.com', res, options);
assert(restRes.statusCode == 200, "statusCode should be 200");
assert(restRes.result && restRes.result.url === 'http://microsoft.com/post');
assert(restRes.result && restRes.result.data === 'url encoded body');
});

it('creates a resource with a baseUrl', async() => {
nock('http://microsoft.com')
.post('/')
Expand Down