Communicate Between Fetch POST And ColdFusion Function With CfHttp - coldfusion

While I understand that fetch() requests can have parameters, in the form of "headers:", "body:", etc., I'm having trouble with a fetch() POST call to a ColdFusion Component remote function.
My fetch call is:
fetch('myComponent.cfc?method=createObj', {method: "POST", body: jsonVar })
.then(function (getCreateResponse) {
//do great things
})
.catch(function err) {
alert("Fetch error: " + err);
});
My cfc function looks like:
remote array function createObj(required any myObj) returnFormat = "JSON" {
cfhttp(url="http://myServer/ObjAPI/Obj", method="POST", result="getResponse") {
cfhttpparam(type="header", name="Content-Type", value="application/json");
cfhttpparam(type="body", value=SerializeJSON(myObj));
} }
(This POST takes a RequestBody with the JSON.) When I run this code, I am told in my CFC logs:
"The MYOBJ parameter to the createObj function is required but was not passed in."
When I remove the parameter from the createObj function, the fetch call fails and I am told:
"Variable MYOBJ is undefined."
It appears to me that the CF Function needs a parameter in order to know what it should send in the cfhttp call; however, it's not recognizing the "body: jsonVar" parameter sent by the fetch call. Is there another way to send a parameter that the CF function would understand?

You are passing the data as body data. You can see the json data as below
remote array function createObj() returnFormat = "JSON" {
WriteDump(deserializeJSON(ToString(getHTTPRequestData().content)));
myObj = deserializeJSON(ToString(getHTTPRequestData().content));
cfhttp(url="http://myServer/ObjAPI/Obj", method="POST", result="getResponse") {
cfhttpparam(type="header", name="Content-Type", value="application/json");
cfhttpparam(type="body", value=SerializeJSON(myObj));
}
}

Related

use jest mock functions to test code that calls another server

Roughly, my JavaScript function that I want to unit-test looks like this:
const request = require('request-promise-native');
async function callServer() {
// Prepare parameters
// Call `request` with parameters
// Parse response JSON and return
}
Is there any way to unit-test this function without making an actual call to the real server? Can I use a jest mock function to somehow override request()? To do that, will I need to modify every function to take the request function as a parameter or there is another way?
You can mock imported module via jest.mock. https://jestjs.io/docs/en/api#requirerequiremockmodulename
describe('main description', () => {
it('description of test case', () => {
jest.mock('request-promise-native', () => {
return {}; // Return what the request-promise-native supposed to return
});
const result = callServer();
expect(result).toBe({});
});
});

Ionic2: platform.is() response is undefined

I'm using the native Bluetooth serial library and trying to mock data for testing in the browser. By experimentation (and a little reading) it seems that the way to do this is to check for the 'cordova' platform:
export class BluetoothServiceWrapper implements OnDestroy, OnChanges {
...
private isEmulated:boolean = true;
...
constructor(platform:Platform) {
platform.ready().then(() => {
this.isEmulated = !platform.is('cordova');
});
}
The strange thing is that this works in some parts:
connect(device:BluetoothDevice) {
return Observable.create(observer => {
...
if (!this.isEmulated) {
...
}else{
... // this is executed in the browser
}
}
}
But in other parts the this.isEmulated is undefined:
write(data:any):Promise<any> {
if (!this.isEmulated) {
return BluetoothSerial.write(data);
} else {
.... // this never gets executed
}
}
Am I overcomplicating this and there is an easier way to check if we are using browser/emulation? Or is there some error in the way the context is being passed over?
I should mention that both methods get the same members when accessing 'this' i.e. the BluetoothServiceWrapper members. In the case of the 'write' function though the isEmulated variable is hidden/undefined.
Ok, this was a bit of a trap. The important piece of information that was missing from the original post was that I had another component/service perform the following:
if (!this.isConnected && (!this.isConnecting)) {
this.bluetoothServiceWrapper.connect(device).subscribe(data => this.tuningModuleService.onData(data), console.error);
this.tuningModuleService.setOutputFunction(this.bluetoothServiceWrapper.write);
}
Inside the service above I would be calling this.write('somedata'), using the function above given as reference.
The service:
outputToSerialFn: any;
constructor(applicationRef: ApplicationRef, platform: Platform) {
...
// default (mock) output function
this.outputToSerialFn = function (data) {
return new Promise((resolve, reject) => {
console.log('Mock BT OUT', data);
})
};
}
setOutputFunction(outputToSerialFn: any) {
this.outputToSerialFn = outputToSerialFn;
}
The problem is that during calls the write function would get the scope of the Service using it instead of the BluetoothWrapper service.
One solution is to replace the call above with:
this.tuningModuleService.setOutputFunction(this.bluetoothServiceWrapper.write.bind(this.bluetoothServiceWrapper));
The key word is bind.
This is probably not the best pattern but might help someone who is also struggling with this. The lesson here is that passing functions as parameters overrides the original function scope.

Laravel testing - Problems with created routes

I have a question about routing while testing packages. The function setRoutes creates new routes in the test file as follows:
class PackageTests extends \Orchestra\Testbench\TestCase {
protected function setRoutes()
{
Route::group([
'prefix' => Package::functionToCall1(),
'before' => 'filter'
], function() {
Route::get('/', function () {
return "hello";
});
});
Route::enableFilters();
}
protected function getEnvironmentSetUp($app)
{
$this->app = $app;
$this->setRoutes();
Config::set('app.url', "http://localhost/" );
}
public function testFunction1()
{
$crawler = $this->call(
'GET',
'http://localhost/'
);
// doing this call, the function on the prefix is called
$this->assertResponseOk();
}
}
Inside the function called in the prefix, functionToCall1() urls are not taken successfully. A call to URL::current() returns "/" and a call to Request::fullUrl() returns "http://:" when phpunit is executed but they returns the full url when used executing a url in the browser. This is the code of the package:
class Package
{
function functionToCall1()
{
var_dump(URL::current() ); // returns "/"
var_dump(Request::fullUrl()); // returns "http://:"
// I want them to return 'http://localhost'
}
}
I tried setting up the url Config::set('app.url', "http://localhost/" ); but it was useless.
To sum up, is there a way to call a function in the prefix and get the testing url?
Thanks, I would really appreciate your answers :)
I have had to deal with a similar issue. My solution was found here:
Mocking Laravel's Request::segment method
Apparently there is an order of operations issue with testing a Request facade.
I was trying to use Request::segments() before the request was being built, so there were never any segments to return.
I imagine it's the same problem with Request::fullUrl().
Here is my solution:
class MyTestClass extends TestCase
{
public function setUp()
{
// No call to parent::setUp()
$this->app = $this->createApplication();
$this->app->request->server->set('REQUEST_URI', '/some/uri');
$this->client = $this->createClient();
$this->app->boot();
}
public function testWhatever()
{
$this->call('GET', '/some/uri');
}
}
This allows me to get the request data properly, even though it looks pretty bad.

Intercepting a REST call with Ember Data

For a particular REST server that I'm working against the DELETE method has two varieties. When called without a query parameter the delete action results in an update taking place where the underlying resource's workflow status is "marked for deletion". If, however, an immediate deletion is the goal than you simply add the query parameter ?immediate=true.
I'd to programmatically send choose which of these varieties to send based on some simple client side logic but I'm not sure how I would get my query parameter added to the DELETE request.
In both cases, I'm assuming that calling DS.Model's .destroyRecord() or .deleteRecord() is appropriate. I'm also wondering if this is a case where I would need to create a custom DS.Adapter. I'd love to avoid that but if I must do it are there any good examples of this? Is there a way to inherit the implementation of all adapter methods and only override what needs changing (the documentation indicated that DS.Adapter is purely abstract)?
One solution would be to to override the RESTAdapter:
App.ProductAdapter = DS.RESTAdapter.extend({
deleteRecord: function(store, type, record) {
//do ajax stuff here
//return a promise that resolves or rejects based on ajax outcomes
return new Em.RSVP.Promise( function(resolve, reject){ resolve(); } );
},
})
The following is not required but I use it to wrap my ajax request in a promise:
function ajaxPromise (url, type, hash) {
return new Ember.RSVP.Promise(function(resolve, reject) {
hash = hash || {};
hash.url = url;
hash.type = type;
hash.dataType = 'json';
hash.success = function(json) {
Ember.run(null, resolve, json);
};
hash.error = function(json) {
if (json && json.then) { json.then = null }
Ember.run(null, reject, json);
};
$.ajax(hash);
});
}
You can then pass it type DELETE with any additional parameters in the hash or add them to the URL. e.g.
deleteRecord: function(store, type, record) {
var promise = new ajaxPromise(URL, "DELETE", hash);
promise.then(function(result){
//do stuff here with result
});
return promise
}

TypeError: Error #1010: web service as3 + wcf

I have a simple webservice returning object list of books. I am trying to take this collection with aducentes web service class, but I get the type error:
TypeError: Error #1010: A term is undefined and has no properties.
Can anyone help to pull object into
array and trace the result?
import alducente.services.WebService;
import flash.events.*;
var ws:WebService = new WebService();
ws.addEventListener(Event.CONNECT, connected);
ws.connect("http://localhost:8732/Design_Time_Addresses/TestService/Service1/?wsdl");
ws.cacheResults = true;
var initTime:Number;
function connected(evt:Event):void{
// var books:Array=ws.IBookService.GetBooks();
// trace(books[0]);
var obj:Object=ws.IBookService.GetBooks();
// var obj:Object=ws.IBookService.GetBooks();
// trace(obj[0].toString());
}
Just thought of something else... In the version of WebService I used a while back, you have to specify a resultHandler function with each method call:
function connected(evt:Event):void{
ws.IBookService.GetBooks( getBooksResultHandler );
}
function getBooksResultHandler( resultXML : XML ) : void {
doStuffWith(resultXML);
}
The result will be passed to the handler you've passed as a parameter.