I am looking to get the created deployment id returned in the callback, how do I get it immediately when it is created ?
This is from the jsforce documentation. Here it is called only when it is completed.
var fs = require('fs');
var zipStream = fs.createReadStream("./path/to/MyPackage.zip");
conn.metadata.deploy(zipStream, { runTests: [ 'MyApexTriggerTest' ] })
.complete(function(err, result) {
if (err) { console.error(err); }
console.log('done ? :' + result.done);
console.log('success ? : ' + result.true);
console.log('state : ' + result.state);
console.log('component errors: ' + result.numberComponentErrors);
console.log('components deployed: ' + result.numberComponentsDeployed);
console.log('tests completed: ' + result.numberTestsCompleted);
});
This was dead simple, I was able to figure out this, just use the callback without the complete.
Related
I am trying to get the contents of a .json file using a node js service into an angularjs method. But am getting following error:
_http_outgoing.js:700
throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type object
at ServerResponse.end (_http_outgoing.js:700:13)
here are the corresponding code fragments...
angular controller: the commented lines are all of those which i have tried and failed with.
var currentProcess = "process_1cA";
$scope.storestats = [];
var resAss = $resource('/procs/getstorestats');
var stats = resAss.get({
process: currentProcess,
date: date.getFullYear() + "" + m + "" + d
});
stats.$promise.then(function(response) {
if (response != undefined) {
// var r = JSON.parse(response);
//$scope.storestats.push(r);
//$scope.storestats.push(r);
//var r = JSON.parse(response);
$scope.storestats.push(response);
//angular.forEach(r, function(value, key) {
// $scope.storestats.push({key : value});
//});
}
});
NODEJs service:
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
//var r = data.toString('utf8');
var msgs2 = JSON.stringify(msgs1);
console.log(msgs1);
res.end(msgs1);
});
}
catch (err) {
res.end(err.toString());
}});
P.S: The commented out lines are those which i have tried out with and failed. Also, the commented lines in the node service code snippet, give no error, and when logged show it correctly, but the data when in response of the controllers is blank.
I'm guessing a bit here, but I think you just need to change res.end() to res.send() in your Node code. The "end" method is used when you are streaming chunks of data and then you call end() when you're all done. The "send" method is for sending a response in one go and letting Node handle the streaming.
Also, be sure you are sending a string back!
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
//var r = data.toString('utf8');
var msgs2 = JSON.stringify(msgs1);
console.log(msgs1);
res.send(msgs2); // NOTE THE CHANGE to `msg2` (the string version)
});
}
catch (err) {
res.send(err.toString()); // NOTE THE CHANGE
}
});
I had a similar error. It was because I was passing process.pid to res.end(). It worked when I changed process.pid to string
res.end(process.pid.toString());
Figured it out. 2 small changes were needed.. One in the controller, which was to use a "$resource.query" instead of "$resource.get". And in the service, as #jakarella said, had to use the stringified part in the .end();
Controller:
var resAss = $resource('/procs/getstorestats');
var stats = resAss.query({process: currentProcess, date: date.getFullYear() + "" + m + "" + d});
stats.$promise.then(function (response) {
$scope.storestats.push(response);
}
Node Service:
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
var msgs2 = JSON.stringify(msgs1);
console.log(msgs2);
res.end(msgs2);
});
}
If you are using 'request-promise' library set the json
var options = {
uri: 'https://api.github.com/user/repos',
qs: {
access_token: 'xxxxx xxxxx'
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(function (repos) {
})
.catch(function (err) {
});
Thank you user6184932, it work
try {
await insertNewDocument(fileNameDB, taskId);
res.end(process.pid.toString());
} catch (error) {
console.log("error ocurred", error);
res.send({
"code": 400,
"failed": "error ocurred"
})
}
in mysql2 the reason for the error is the sql word , sql is a query :
const sql = select * from tableName
pool.executeQuery({
sql,
name: 'Error list for given SRC ID',
values: [],
errorMsg: 'Error occurred on fetching '
})
.then(data => {
res.status(200).json({ data })
})
.catch(err => {
console.log('\n \n == db , icorp fetching erro ====> : ', err.message, '\n \n')
})
I got the error using Node v12 (12.14.1).
Uncaught TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type number
Sample code for context.
const { Readable } = require('stream')
Readable.from(Buffer.from(base64content, 'base64'))
.pipe( ... )
Solution (for my case), was upgrading to Node v14 (14.17.3). e.g.
nvm use 14
nvm
i have an ion-slide component with 3 slides. when running the app the first time, all three slides load. however, going to another controller and coming back to the controller where the ion-slide is (using $state.go), only displays one slide and has the following error:
TypeError: Cannot read property '0' of undefined
seeing this error, i traced it passes through this line first:
sharedProperties.setProperty($scope.cardNumbers[$scope.currentIdx]
.CardNumber);
instead of this code fetching the card number:
var url = 'http://10.10.9.169/UserService3/WebService1.asmx';
$http.get(url + '/getCardsbyUsername' + '?unameID=' + currentID ).success(function(response) {
// stuff
console.log('response is jsonobj = ' + response);
var strObj = JSON.stringify(response).replace(/"(\w+)"\s*:/g, '$1:');
var myObject = eval('(' + strObj + ')');
$scope.cardNumbers = myObject;
console.log('response is jsonarr = ' + $scope.cardNumbers);
})
.error(function(response) {
// error stuff
console.log('response error is = ' + response);
});
here's the full code:
$scope.currentIdx = 0;
var currentID = sharedProperties3.getUserID();
console.log('current ID = ' + currentID);
var url = 'http://10.10.9.169/UserService3/WebService1.asmx';
$http.get(url + '/getCardsbyUsername' + '?unameID=' + currentID ).success(function(response) {
// stuff
console.log('response is jsonobj = ' + response);
var strObj = JSON.stringify(response).replace(/"(\w+)"\s*:/g, '$1:');
var myObject = eval('(' + strObj + ')');
$scope.cardNumbers = myObject;
console.log('response is jsonarr = ' + $scope.cardNumbers);
})
.error(function(response) {
// error stuff
console.log('response error is = ' + response);
});
$scope.options1 = {
initialSlide: 0,
onInit: function(slider1)
{
$scope.slider1 = slider1;
sharedProperties.setProperty($scope.cardNumbers[$scope.currentIdx].CardNumber);
},
onSlideChangeEnd: function(slider1)
{
console.log('The active index is ' + slider1.activeIndex);
$scope.currentIdx = slider1.activeIndex;
console.log('The active card is ' + $scope.cardNumbers[$scope.currentIdx].CardNumber);
sharedProperties.setProperty($scope.cardNumbers[$scope.currentIdx].CardNumber);
}
};
$scope.options2 = {
direction: 'vertical',
slidesPerView: '1',
pagination: false,
initialSlide: 1,
showNavButtons: false
};
how can i make it pass through the $http.get code block first?
i noticed i was loading angularjs more than once, so i got rid of the extra code calling angularjs in my index.html and it worked.
I am using ngMock for unit testing and I need to use the $timeout.flush function in one of my tests, so I have added the two following lines to my test:
$timeout.flush();
$timeout.verifyNoPendingTasks();
as indicated on http://www.bradoncode.com/blog/2015/06/11/unit-testing-code-that-uses-timeout-angularjs/.
$timeout.flush() does flush the timeout as expected, however I am now getting an exception from angular-mocks.js every time I run my test:
LOG: 'Exception: ', Error{line: 1441, sourceURL: 'http://localhost:9876/base/node_modules/angular-mocks/angular-mocks.js?05a191adf8b7e3cfae1806d65efdbdb00a1742dd', stack: '$httpBackend#http://localhost:9876/base/node_modules/angular-mocks/angular-mocks.js?05a191adf8b7e3cfae1806d65efdbdb00a1742dd:1441:90
....
global code#http://localhost:9876/context.html:336:28'}, 'Cause: ', undefined
Does anyone know where this exception could come from? I get it as many times as I use the $timeout.flush() function.
Looking at the angular-mocks.js file, it looks like it comes from the $httpBackend function. I have tried to update the ngMock version but it does not change anything. I have tried version 1.4.7 (which is my angular version) and version 1.6.2.
function $httpBackend(method, url, data, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
var xhr = new MockXhr(),
expectation = expectations[0],
wasExpected = false;
xhr.$$events = eventHandlers;
xhr.upload.$$events = uploadEventHandlers;
function prettyPrint(data) {
return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
? data
: angular.toJson(data);
}
function wrapResponse(wrapped) {
if (!$browser && timeout) {
if (timeout.then) {
timeout.then(handleTimeout);
} else {
$timeout(handleTimeout, timeout);
}
}
return handleResponse;
function handleResponse() {
var response = wrapped.response(method, url, data, headers, wrapped.params(url));
xhr.$$respHeaders = response[2];
callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(),
copy(response[3] || ''));
}
function handleTimeout() {
for (var i = 0, ii = responses.length; i < ii; i++) {
if (responses[i] === handleResponse) {
responses.splice(i, 1);
callback(-1, undefined, '');
break;
}
}
}
}
if (expectation && expectation.match(method, url)) {
if (!expectation.matchData(data)) {
throw new Error('Expected ' + expectation + ' with different data\n' +
'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
}
if (!expectation.matchHeaders(headers)) {
throw new Error('Expected ' + expectation + ' with different headers\n' +
'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
prettyPrint(headers));
}
expectations.shift();
if (expectation.response) {
responses.push(wrapResponse(expectation));
return;
}
wasExpected = true;
}
var i = -1, definition;
while ((definition = definitions[++i])) {
if (definition.match(method, url, data, headers || {})) {
if (definition.response) {
// if $browser specified, we do auto flush all requests
($browser ? $browser.defer : responsesPush)(wrapResponse(definition));
} else if (definition.passThrough) {
originalHttpBackend(method, url, data, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers);
} else throw new Error('No response defined !');
return;
}
}
throw wasExpected ?
new Error('No response defined !') :
new Error('Unexpected request: ' + method + ' ' + url + '\n' +
(expectation ? 'Expected ' + expectation : 'No more request expected'));
}
I want to setup JS exception logging module in my angularJS application and for this I am using $exceptionHandler.
I am using following code to log app errors :
app.config(function($provide) {
$provide.decorator("$exceptionHandler", function($delegate) {
return function(exception, cause) {
$delegate(exception, cause);
// alert(exception.message);
console.log(JSON.stringify(exception.message += ' (caused by "' + cause + '")'));
};
});
});
But here,I am getting only message but I want all details related to exception like errorMsg, url, line number etc.
How to get all this details using above code?
As it turns out the only part of the error object that's standardized is the message. Both lineNumber, and fileName will give inconsistent results across different browser versions.
The most general way of getting as much detail about the exception that you can might be this:
app.config(function($provide) {
$provide.decorator("$exceptionHandler", function($delegate) {
return function(exception, cause) {
$delegate(exception, cause);
var formatted = '';
var properties = '';
formatted += 'Exception: "' + exception.toString() + '"\n';
formatted += 'Caused by: ' + cause + '\n';
properties += (exception.message) ? 'Message: ' + exception.message + '\n' : ''
properties += (exception.fileName) ? 'File Name: ' + exception.fileName + '\n' : ''
properties += (exception.lineNumber) ? 'Line Number: ' + exception.lineNumber + '\n' : ''
properties += (exception.stack) ? 'Stack Trace: ' + exception.stack + '\n' : ''
if (properties) {
formatted += properties;
}
console.log(formatted);
};
});
});
Let's say you have an Angular app that's showing a list of places. There is a button to get your current location, and clicking the button orders the list according to distance from your location, nearest first.
To test this in Protractor you want to be able to click the button and inspect the list:
it('Should order items according to distance', function () {
locButton.click();
expect(...).toBe(...); // Check that the first item on the list
// the closest to the given lat/long
});
Now, let's say the button calls a method in a controller, the controller calls a method in a service, and the service calls navigator.geolocation.getCurrentPosition() (and, for good measure, that call is wrapped in a promise). The best way to test this is to mock the call to getCurrentPosition() and return a specific latitude and longitude, so that has the required effects all the way back up the chain to the page output. How do you set that up that mock?
I tried the method in this answer to a similar question about Jasmine, creating a spy on navigator.geolocation, with the result:
ReferenceError: navigator is not defined
I also tried mocking the service with something similar to this answer with the result:
ReferenceError: angular is not defined
Update:
Found a solution so I answered my own question below, but I'm really, really hoping there's a better answer than this.
Found a way to do it by using browser.executeScript() to run some JavaScript directly in the browser. For example:
describe('Testing geolocation', function () {
beforeEach(function () {
browser.executeScript('\
window.navigator.geolocation.getCurrentPosition = \
function(success){ \
var position = { \
"coords" : { \
"latitude": "37",
"longitude": "-115" \
} \
}; \
success(position); \
}')
});
it('Should order items according to distance', function () {
locButton.click();
expect(...).toBe(...); // Check that the first item on the list
// the closest to the given lat/long
});
});
This works, but it's ugly. I did my best to make the string passed to browser.executeScript() as readable as possible.
EDIT
Here's a cleaned up version with two functions to mock successes and errors:
describe('Geolocation', function () {
function mockGeo(lat, lon) {
return 'window.navigator.geolocation.getCurrentPosition = ' +
' function (success, error) {' +
' var position = {' +
' "coords" : {' +
' "latitude": "' + lat + '",' +
' "longitude": "' + lon + '"' +
' }' +
' };' +
' success(position);' +
' }';
}
function mockGeoError(code) {
return 'window.navigator.geolocation.getCurrentPosition = ' +
' function (success, error) {' +
' var err = {' +
' code: ' + code + ',' +
' PERMISSION_DENIED: 1,' +
' POSITION_UNAVAILABLE: 2,' +
' TIMEOUT: 3' +
' };' +
' error(err);' +
' }';
}
it('should succeed', function () {
browser.executeScript(mockGeo(36.149674, -86.813347));
// rest of your test...
});
it('should fail', function () {
browser.executeScript(mockGeoError(1));
// rest of your test...
});
});
Protractor tests are e2e, so you really do not have access to your backend code and results.
I had a similar issue in that I wanted to see my "post" output when I click submit in a form.
Created this that populates a test results in the dom, so you can see such backend stuff like this.
Not the best, but do not see another way to do this.
/////////////////////////////////////////////////////////////////
//markup added for testing
<div ng-controller="myTestDevCtrl">
<button id="get-output" ng-click="getOutput()">get output</button>
<input ng-model="output" />
</div>
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
//test controller to show ajax data coming out
myTestModule.controller('myTestDevCtrl', function($scope,dataProxy) {
$scope.getOutput = function() {
$scope.output = dataProxy.getData();
}
})
//small service to capture ajax data
.service('dataProxy',function() {
var data;
return {
setData : function(_data) {
data = decodeURIComponent(_data);
},
getData : function() {
return data;
}
}
})
.run(function($httpBackend,dataProxy) {
//the office information post or 'save'
$httpBackend.when('POST',/\/api\/offices/)
.respond(function (requestMethod, requestUrl, data, headers) {
//capture data being sent
dataProxy.setData(data);
//just return success code
return [ 200, {}, {} ];
});
});
//make myTestModule require ngMockE2E, as well as original modules
angular.module('myTestModule').requires = [
'ngMockE2E'
];
/////////////////////////////////////////////////////////////////