Trying to call an API using a trigger and get data - arrays

I am very new at this and I am trying my best to work it out. It would be glad if someone can really save my day.
Trying to call an API using a trigger and get data using google scripts this is the best I came up with.
Basically I have an api which gives me objects if I putit in Postman. All I need to do it get those object in google spreadsheets.
I have tried onOpen function which was giving me an error of" You do not have permission to call Fetch".
So have been trying with on edit of first column as "Get Data" so the api can be called.
Thanks in advance
function onEdit(e) {
var s = SpreadsheetApp.getActiveSheet();
if (s.getName() == "Sheet1") { //checks that we're on the correct sheet
var r = s.getActiveCell();
//Updates timestamp for lead entry and meetings.
var currentCellValue = r.getValue();
var user = Session.getEffectiveUser();
if (r.getColumn() == 1 && (currentCellValue == 'Get Data')) { //checks the column
var nextCell = r.offset(0, 4);
if (nextCell.getValue() == '') { //is empty?
nextCell.setValue(Utilities.formatDate(new Date(), "GMT+5:30", "dd/MM/yyyy HH:mm:ss")).setComment(user);
var url = "My API";
var headers = {
"Content-Type": "application/json",
"Authorization": "userkey"
};
var options = {"method":"GET","headers": headers
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response[0]);
}
}
}
}

This appears to be a long standing issue that still hasn't been taken care of, see here
Someone in the thread mentions
But, using a custom function name like myOnEdit(), and connecting it
to the onEdit event manually, totally works!
function myOnEdit(e) { ... var x = fetchUrlApp.fetch(...); ... }
So you have to create myOnEdit and then put an onEdit trigger on it, either via Resources > Current Project's triggers or via the trigger service.

Related

Last Element is not getting stored in to an array in flutter?

I am trying to store a response from the API to a list, the responses are getting stored but last element is not getting stored in the list.
var selectedImage = [];
if (_image.length > 0) {
for (var img in _image) {
var request = http.MultipartRequest(
'POST', Uri.parse('url'));
request.fields.addAll({'userPath': "${widget.scanQr}"});
var process = await http.MultipartFile.fromBytes(
'file', File(img.path).readAsBytesSync(),
filename: img.path.split("/").last,
contentType: MediaType('image', 'jpg'));
request.files.add(process);
var response = await request.send();
print(response.statusCode);
if (response.statusCode == 200) {
response.stream.transform(utf8.decoder).listen((value) {
print("The value is $value");
selectedImage.add(value);
});
print(selectedImage);
}
The response I get when try to insert 2 images is:
[/uploads/jdsfei884ri4h449898/activity/file_1637650234094]
the first image is stored but the 2nd image didn't get stored.
listen is not a syncronous method. You do not wait on it to finish, so when your piece of code is done, you have no idea if the stream listeners have already done their work. They might have added to the result array, or they might not have.
I suggest you use a method that ensures it did it's job before you move on.
It seems your stream only has one element anyway:
if (response.statusCode == 200) {
const value = await stream.transform(utf8.decoder).first;
selectedImage.add(value);
}
Replace selectedImage.add(value); with selectedImage.addAll(value);
You are getting ArrayList from API, So basically add function add only object and addAll function add your whole list.

Retrieve details on Bus Line or Subway in Google Map API

I'm looking for doing something like this website : WEBSITE GMAPS
For the moment i can get everything around 500meters like if it's a bus stop or something else but i can't retrieve the Bus line.
var mapControl = $scope.map.control.getGMap();
service = new google.maps.places.PlacesService(mapControl);
var transitLayer = new google.maps.TransitLayer();
transitLayer.setMap(mapControl);
var directionsService = new google.maps.DirectionsService();
service.search(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
$scope.placesTransit = [];
$scope.timeTotal = [];
angular.forEach(results, function(result, key) {
var timeTotal;
directionsService.route(
{
origin: new google.maps.LatLng($scope.map.center.latitude, $scope.map.center.longitude),
destination: result.geometry.location,
travelMode: google.maps.DirectionsTravelMode.WALKING,
unitSystem: google.maps.UnitSystem.METRIC
}, function (response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
result.timeTotal = response.routes[0].legs[0].duration.text;
if (result.types[0] === "subway_station") {
result.typeTransport = "Métro";
}
console.log(result);
$scope.placesTransit.push(result);
}
});
});
}
}
If someone can helps me how to do that :
Apparently i can retrieve this information on this page , but there's nothing to get this with Google MAP API v3 . Any Idea ? Thanks
Yes, Google has a place where you can get the information about public transportation.
First, you need to check if your city is supported:
https://maps.google.com/landing/transit/cities/
Then, if it is supported you can get more information here:
https://maps.google.com/landing/transit/index.html
To access it programatically, you can both the following APIs:
https://developers.google.com/transit/
https://developers.google.com/maps/documentation/directions/
I would go with the second one.
With this in mind, if the company you are trying to check is registered, you will be able to easily access all of its bus routes (and more).
If the company is not listed however, it means that they coded the path on the map that you see, and you must do the same using overlays:
https://developers.google.com/maps/documentation/javascript/examples/overlay-simple
Hope it helps!

Download a file in Angular Environment

I need to download a file from the server. The file is stored in the database. I have a cs controller that serves a file back to UI. The server GET call looks like this:
http://server/api/controllername/fileid/data
It does work when I run that link in the Browser - the file comes down and goes into the download area (Chrome). But when I send the same command from my Angualar code I dont see any file. The console reports that my request was successful (code 200), but I just dont see anything. Please let me know what code fragments to post to make it easier to help.
Thanks
Create a link to the resource, and don't handle it with ajax.
If you make the link open in a new tab, the tab will automatically close after it realises it was just opened to download a file in most modern browsers.
Try this code:
var a = document.createElement('a');
a.href = "http://server/api/controllername/fileid/data";
a.click();
You can compose the address concatenating variables and text.
The file probably downloads correctly as a byte[] to the calling it but that would be useless to the user - as was my problem.
In my case I needed to download a file with a complex set of parameters. This example JavaScript uses a post request and creates a form (and posts it) with any JavaScript object that you give it. This code may help if you simplified it:
private open(verb, url, data, target)
{
var form = document.createElement("form");
form.action = url;
form.method = verb;
form.target = target || "_self";
if (data) {
this.createFormParameters(form, "", data);
}
form.style.display = 'none';
document.body.appendChild(form);
form.submit();
}
private createFormParameters(form, key, value) {
// recursive algorithm to add parameters (including objects and arrays of objects) to a custom form
if (typeof value === "object") {
for (var item in value) {
if (Array.isArray(value[item])) {
for (var arrayItem in value[item]) {
this.createFormParameters(form, (item + "[" + arrayItem + "]."), value[item][arrayItem]);
}
continue;
}
var input = document.createElement("textarea");
input.name = key + item;
input.value = value[item];
form.appendChild(input);
}
}
else
{
var input = document.createElement("textarea");
input.name = key;
input.value = value;
form.appendChild(input);
}
}

Why won't this code work to create a Parse object in an Ionic app?

I'm trying to create a Parse object in an app using the Ionic Framework, and I can't get it to work. I'm fairly new to programming, but I've been able to create Parse users, just not objects. Can anyone help me find a solution? Please see the code below for my controller in question. Thanks!
.controller('AddProspectsController', function($scope, $state, $rootScope) {
if (!$rootScope.isLoggedIn) {
$state.go('welcome');
}
$scope.prospect = {};
$scope.error = {};
// Syntax to create a new subclass of Parse.Object.
//var Prospects = Parse.Object.extend("Prospects");
$scope.addProspect = function() {
// Create a new instance of that class.
var Prospects = Parse.Objext.extend("Prospects");
var prospects = new Prospects();
prospect.set("name", $scope.prospect.name);
prospect.set("phone", $scope.prospect.phone);
prospect.set("email", $scope.prospect.email);
prospect.set("interest", $scope.prospet.interest);
prospect.save(null, {
success: function(prospect) {
// Execute any logic that should take place after the object is saved.
$state.go('app.prospects', {clear: true});
alert('New object created with objectId: ' + prospect.id);
},
error: function(prospect, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
alert('Failed to create new object, with error code: ' + error.prospect);
}
});
}
})
You have another spelling error on this line:
var Prospects = Parse.Objext.extend("Prospects");
This is not Objext, but Object.​​​​​​
I hope this will help.
There is a spelling error... you have the variable named prospects with an "s" and when you are creating the object, you are using a variable named prospect

Angular $resource and use of Interceptor to check response/error/callback

Last few days I am working to invoke REST services and track the response, error, callback etc. I have gone through most of the posting however due to my limited understanding on Angular seems like I am not able to understand it. Following is my problem and understanding I got so far.
I am using Project.$update() service which returns only "project_id". This server doesn't return complete data again. Following is line of few line of code to share here.
//create Project factory
app.factory('Project', function ($resource) {
return $resource('/api/projects/:projectid',
{projectid:'#id'},
{update: {method:'PUT', isArray:false}}
);
});
Following is code in directive I am using to update/create project.
//save project
scope.saveProject = function (project) {
//update modified by field
project.modifiedby = scope.user._id;
//change to view mode
scope.projectView = 1;
//call server to save the data
if (project._id == undefined || project._id == "") {
//Call server to create new and update projectID
project._id = project.$save()._id;
}
else {
//Call server to update the project data
project.$update({ projectid: project._id });
}
};
Following is service response for both save() and update().
{"_id":"52223481e4b0c4d1a050c25e"}
Problem here is; "project" object value is replaced by new response returned by server having only project_id and other fields are replaced.
I was going through detailed documentation on $resource however I am not able to grasp it. It will be great to get some guidance here to write code to detect error, response, callback.
You can replace the original object by the one returned from the server in your success callback like this:
//save project
scope.saveProject = function (project) {
//update modified by field
project.modifiedby = scope.user._id;
//change to view mode
scope.projectView = 1;
//call server to save the data
if (project._id == undefined || project._id == "") {
//Call server to create new and update projectID
project.$save(function(updatedProject, headers){
// Replace project by project returned by server
project = updatedProject;
});
}
else {
//Call server to update the project data
project.$update(function(updatedProject, headers){
// Replace project by project returned by server
project = updatedProject;
});
}
};
That will replace the original object by the one returned by the server as soon as the server response is received.
If your callback is identical for the $save and $update methods, you can further simplify your code like this:
//save project
scope.saveProject = function (project) {
//update modified by field
project.modifiedby = scope.user._id;
//change to view mode
scope.projectView = 1;
var action = (angular.isDefined(project._id)) ? '$update' : '$save';
//call server to save the data
project[action](function(updatedProject, headers){
// Replace project by project returned by server
project = updatedProject;
});
};
Hope that helps!
As per suggestion made by jvandemo and BoxerBucks; I have used following approach for save/update by passing the callback method with copy of original data. However still I am looking for central approach to take care of error/success status. Please suggest.
//save project metadta
scope.saveProjectMetadta = function (project) {
//update modified by field
project.modifiedby = scope.user._id;
//change to view mode
scope.projectView = 1;
//keep original data to pass into callback
var originalProjectObject = angular.copy(project);
//call server to save the data
if (project._id == undefined || project._id == "") {
//Call server to create new and update projectID
project.$save(originalProjectObject, function (projectResponse) {
originalProjectObject._id = projectResponse._id;
//update scope
scope.project = originalProjectObject;
//invoke method to update controller project object state
scope.updateProjectScope(scope.project);
});
}
else {
//Call server to update the project data
project.$update({ projectid: project._id }, function (projectResponse) {
originalProjectObject._id = projectResponse._id;
//update scope
scope.project = originalProjectObject;
//invoke method to update controller project object state
scope.updateProjectScope(scope.project);
},originalProjectObject);
}
};

Resources