Restivus return HTML template? - meteor

I'm trying to make an api for my METEOR application.
I looked at https://atmospherejs.com/simple/rest and https://atmospherejs.com/xcv58/collection-api but that didn't work.
Now i'm on restivus : https://atmospherejs.com/nimble/restivus
The problem that i got is that when i'm trying to call the api, it always return my HTML template, otherwise i need a json response...
This is my code for the api =>
In server.js :
// Global API configuration
var Api = new Restivus({
apiPath: 'api/',
auth: {
token: 'auth.apiKey',
user: function () {
return {
userId: this.request.headers['user-id'],
token: this.request.headers['login-token']
};
}
},
defaultHeaders: {
'Content-Type': 'application/json'
},
onLoggedIn: function () {
console.log(this.user.username + ' (' + this.userId + ') logged in');
},
onLoggedOut: function () {
console.log(this.user.username + ' (' + this.userId + ') logged out');
},
prettyJson: true,
useDefaultAuth: true,
version: 'v1'
});
Api.addCollection('coupons');
When i try to do curl on http://localhost:3000/api/v1/login/ with some username and password data, it return me all my html template...
Someone know the solution or already have this problem ?
Thanks for your future answers :)

The problem is that you're using the set of API options that the docs warn against using. Check the comment directly above the code here. If you want to copy and paste some code to get started, you can use the code from the quick start example. All you need is the following to get the API you're looking for:
var Api = new Restivus({
useDefaultAuth: true,
version: v1
});
Api.addCollection('coupons');

You should set this header: Content-Type: 'application/x-www-form-urlencoded;charset=UTF-8'
in your request

Related

How to use SailsJs with firebase functions

I'm trying to create nodejs app with sails.js and firebase. Cannot understand how to access express part of SailsJs.
Firebase app initialized by
exports.app = functions.https.onRequest(app);
app - express app.
Sails app initialized by
sails.lift(rc('sails'));
Tried to access to sails.hooks.http.app but it is undefined. Any ideas?
Thanks
hi you can use this piece of code to to execute fire base messaging services and in same manner other services too
var request = require('request');
function sendMessageToUser(deviceId, message) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key=AI...8o'
},
body: JSON.stringify(
{ "data": {
"message": message
},
"to" : deviceId
}
)
}, function(error, response, body) {
if (error) {
console.error(error, response, body);
}
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage+'\n'+body);
}
else {
console.log('Done!')
}
});
sendMessageToUser(
"d7x...KJQ",
{ message: 'Hello puf'}
);
as sails provide a method mentioned below ,but i was not able find exact example to implement Firebase with it so i used core node to explain it , I will be updating this answer after i finished with this method and sails + Firebase
res.created()
hope this helps you in your work

HTTP request to a google service returns Error: read ECONNRESET firebase cloud functions

I am trying to translate the name of a user from english to an indian language using google translate api and storing the data back in realtime database with a cloud function.
This function is invoked by a write to the database, and I am using a HTTP POST request to send a request to the cloud translate api and the response is stored back to the database. My code for the translate request is this.
var translate_options = { method: 'POST',
url: 'https://translation.googleapis.com/language/translate/v2',
qs:
{ key: 'key goes here',
},
form: {
q: fullData.name,
target: "te"
},
};
request(translate_options, function (error, translate_response, translate_body) {
if (error){
console.log("In translating, got an error");
console.log(error);
}
// Query to the database goes here.
});
This code, if tried in my laptop, gives me the correct translation, but if I deploy it as a cloud function, it gives me an error. Very specifically
{ Error: read ECONNRESET
at exports._errnoException (util.js:1020:11)
at TLSWrap.onread (net.js:568:26) code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
I am on firebase blaze plan, and I am able to sent POST request to my other services, but not a google service.
Can anybody help me with this issue. Thanks in advance.
Edit :
The full code is
var functions = require('firebase-functions');
var admin = require('firebase-admin');
var request = require("request");
admin.initializeApp(functions.config().firebase);
exports.whenUserIsAdded = functions.database.ref('users/{companyId}/{uid}').onCreate(event => {
var fullData = event.data.val();
var lang_code = {
"bengali": "bn",
"telugu": "te",
"english": "en"
}
var lang_var = lang_code[fullData['edition']];
var translate_options = { method: 'POST',
url: 'https://translation.googleapis.com/language/translate/v2',
qs:
{ key: 'Key goes here',
},
form: {
q: fullData.name,
target: lang_var
},
};
request(translate_options, function (error, translate_response, translate_body) {
var farmer_name = "";
if(error){
console.log("There is an error in translation");
console.log(error);
}
translate_body = JSON.parse(translate_body);
if(translate_body.data.translations){
farmer_name = translate_body.data.translations[0].translatedText;
console.log("The farmer name is " + fullData.name +" : " + farmer_name);
// Code to write to the database;
} else{
console.log("The translation failed");
farmer_name = fullData.name;
console.log("The famrer name is " + farmer_name);
}
})
});
You're not returning a promise that's resolved when all the work of your function is complete. If the work was completing in the past, that possibly just means you were lucky. Without returning a promise, Cloud Functions may terminate and clean up any work that wasn't complete when the function returns. Properly returning a promise will prevent Cloud Functions from cleaning up before the work is done.
Please consider reading my blog post about this. There is a section special just for ECONNRESET.

ASP.NET oData patchValue received from Angular is nothing

I'm developing an app with an Angular based front-end and an ASP.NET back end using oData and Oracle. I'm at the point where I'm trying to patch records on the back end. I'm using generic boilerplate code on the back end in my controller and the patch method looks like this:
<AcceptVerbs("PATCH", "MERGE")>
Async Function Patch(<FromODataUri> ByVal key As Decimal, ByVal patchValue As Delta(Of FTP_ORDERS)) As Task(Of IHttpActionResult)
Validate(patchValue.GetEntity())
If Not ModelState.IsValid Then
Return BadRequest(ModelState)
End If
Dim fTP_ORDERS As FTP_ORDERS = Await db.FTP_ORDERS.FindAsync(key)
If IsNothing(fTP_ORDERS) Then
Return NotFound()
End If
patchValue.Patch(fTP_ORDERS)
Try
Await db.SaveChangesAsync()
Catch ex As DbUpdateConcurrencyException
If Not (FTP_ORDERSExists(key)) Then
Return NotFound()
Else
Throw
End If
End Try
Return Updated(fTP_ORDERS)
End Function
On the Angular side, I'm using $resource based service to send the update. The code that calls the resource looks like this:
(new FTPOrderService({
"key": vm.ID,
"data": vm
}, vm))
.$patch()
.then(function (data) {
alert("Order Saved!");
},
function (error) {
debugger;
}
);
The service is defined with:
.factory('FTPOrderService', function ($resource) {
var odataUrl = '../odata/FTP_ORDERS';
var results = $resource('', {}, {
'patch': {
method: 'PATCH',
params: {
key: '#key',
},
url: odataUrl + '(:key)'
}
});
return results;
})
I've also tried:
(new FTPOrderService({
"key": vm.ID,
}, vm))
.$patch(vm)
.then(function (data) {
alert("Order Saved!");
},
function (error) {
debugger;
}
);
and get the same results.
I believe that I have configured angular to send the data properly with:
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.patch = {
'Content-Type': 'application/json;charset=utf-8'
};
}])
The debugger shows that I'm calling the URL with the appropriate key appended to it in parens and the request payload looks like this:
{key: "1239990990", data: {loading: false, selectedRow: {}, lineItems: [,…], orderId: "1239990990",…}}
data: {loading: false, selectedRow: {}, lineItems: [,…], orderId: "1239990990",…}
key: "1239990990"
Any idea of what I'm missing? There are numerous examples out there using direct calls to $http.post and a few for .patch, but nothing current using $resource.
I am not entirely sure what the cause of this issue was, but in tracing it, I did discover that intermittently an object was not being received by the patch method in .NET. The object I'm passing in is particularly heavy and what I was passing by default was actually heavier than what the ASP.NET side of the app requires. Adding code prior to the patch call to assemble an object that meets the requirements at a minimum level resolved the issue.

Empty Facebook friends list

So I'm using the "Facebook-sdk" plugin. I'm initializing Facebook like this:
FB.init({ appId: 'xxxxxxxxxxx', cookie: true, xfbml: true, oauth: true, status: true });
FB.login(function(){ // get permissions
}, {scope: 'user_friends, read_friendlists, user_photos, email, publish_actions '});
FB.getLoginStatus(function (response) { // to generate AccessToken
if (response.authResponse) {
console.log('LoginStatusResponse: ' + JSON.stringify(response, null, 4));
} else {
console.log('AuthResponse: No');
}
});
Then in response to a button click event, I'm doing:
'click #get_fb_friends' : function(event, template) {
FB.api(
"/me/friends",
function (response) {
if (response && !response.error) {
console.log('GOT them !!!' + JSON.stringify(response, null, 4));
return response;
} else {
console.log('No can do' + JSON.stringify(response, null, 4));
}
});
}
The thing is that I'm getting an empty Data variable:
GOT them !!!{
"data": []
}
PS: The query "/me" returns all information about myself, it's the "/me/friends" that doesn't work.
Can it be a permissions problem ?
Facebook has changed its api a few weeks ago,you can only access a list of your friends when they have personally accepted to use your app.. Nothing to do about it
Like #Wampie said, the API has changed, so you could try to use the v1 API (keep in mind that you'll need to request a new access token).
And you can still invite friends to your app by using the apprequests method.
FB.ui({
method: 'apprequests',
message: 'You should learn more about the Platform.'
}, function(){
console.log(arguments);
});
Example here:
https://www.fbrell.com/fb.ui/apprequests

AngularJS - Unknown provider configuring $httpProvider

In the following code example:
myApp.config(['$httpProvider', function($httpProvider, $cookieStore) {
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.headers.get['Authorization'] = 'Basic '+ $cookieStore.get('myToken');
return JSON.stringify(data);
}]);
I get an angularjs error like 'Unknown provider $cookieStore'.
'myApp' has dependenciy and 'ngCookies' and angular-cookies.min.js is laoded, so what's wrong with that code ?
Is that fact that i'm doing this in .config ?
Because it's only possible to pass providers when configuring, i have finally done the overwrite of my http parameter not with a request transformer but by creating a service as factory to do requests.
Here is a code example of the service (not tested, just for information):
angular.module('myapp-http-request', []);
angular.module('myapp-http-request')
.factory('MyRequests', function($http, $cookieStore){
return {
request: function(method, url, data, okCallback, koCallback){
$http({
method: method,
url: url,
data: data
}).success(okCallback).error(koCallback);
},
authentifiedRequest: function(method, url, data, okCallback, koCallback){
$http({
method: method,
url: url,
data: data,
headers: {'Authorization': $cookieStore.get('token')}
}).success(okCallback).error(koCallback);
}
}
});
And example of usage (not tested, just for information):
angular.module('sharewebapp', ['myapp-http-request'])
.controller('MyController', ['MyRequests', function(MyRequests){
MyRequests.authentifiedRequest('DELETE', '/logout', '', function(){alert('logged-out');}, function(){alert('error');})
}]);
You probably need to add the cookieStore
myApp.config(['$httpProvider', '$cookieStore', function($httpProvider, $cookieStore)
I had ran into this same problem so i'll post how I got around it. I essentially used the $injector module to manual grab an instance of the service I needed. Note this also works for user defined services.
angular.module('app').
config(config);
config.$inject = ['$httpProvider'];
function config($httpProvider) {
//Inject using the $injector
$httpProvider.interceptors.push(['$injector', function($injector){
return {
request: function(config) {
//Get access by injecting an instance of the desired module/service
let $cookieStore = $injector.get('$cookieStore');
let token = $cookieStore.get('your-cookie-name');
if (token) {
config.headers['x-access-token'] = token;
}
return config;
}
}
}])
}
Using the Module.run() seems to be a cleaner way to set headers that are always needed. See my answer here: AngularJS pass requestVerificationToken to a service

Resources