Making HTTP requests from within MongoDB Atlas App Services - mongodb

We are currently using the Third-party HTTP Service provided by MongoDB in order to make HTTP requests to the outside world from within our app running in Atlas App Services. As per their documentation, this will be deprecated in December 2022.
However, I can't find an alternative for the future - what will be the preferred way to make HTTP requests from within Atlas App Services Apps?

I was in similar situation before as you are.
But then I realised that App Service team actually simplifies it by adding support for dependencies.
So, I can import standard axios library and starts using it seamlessly as
exports = async function(arg){
const axios = require('axios'); // is allowed here
axios.get('https://coderower.com')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
return {success: true}
};

Related

Can i connect to mongodb from my express app hosted on firebase dynamic hosting?

I am trying to connect to mongodb from my express app hosted on firebase dynamic hosting. I simply created an endpoint to save a data on mongodb. This endpoint can be called from localhost(works fine) but fails to load the page on firebase deploy(Error: could not handle the request)
const chris = new User({
name: 'john',
username: `test`,
password: `${Date.now()}`
});
app.get('/user', (request, response) => {
chris.save( (err) => {
if(err) {
response.send(`error occured`);
}
response.send(`${Date.now()}`);
});
});
The issue is that there is a restriction to use network calls (Third party service calls) in the free plan.
**Answer found in Cloud Functions for Firebase - Billing account not configured**d
The restriction is about outbound access - e.g. can your Function request resources from the general internet. Its absolutely fine to use a function to respond to a webhook, or to access Google-internal services such a the Realtime Database.
If you wanted to call a third party web service (for example) you'd need to enable billing.
For the other quotas, take a look at: https://firebase.google.com/pricing/ - as you can see there are limits to the number of invocations (125,000 at time of writing) and CPU and memory (40k cpu-seconds and 40k GB-seconds) in the free tier.

Axios post request is not working in Ionic 2

I'm trying to get oauth token from my laravel app to my ionic 2 app.But it got error. How to solve it ?
It work fine in browser but when i emulate it it doesn't work.
Login.ts (ionic)
getLogin(event) {
oauth_credentials.username = 'rafsanhashemi#gmail.com';
oauth_credentials.password = 'secret';
axios.post(route.oauth_token, JSON.stringify(oauth_credentials),
{headers: {'Content-Type': 'application/json'}})
.then( res => {
console.log(res)
this.selectedItem = res.data;
})
.catch( err => {
console.log(err.data)
this.selectedItem = 'err';
})
}
Error what i got . How to fixed it ?
I advice you to use Angular HttpClient https://angular.io/guide/http
Most front-end applications communicate with backend services over the HTTP protocol. Modern browsers support two different APIs for making HTTP requests: the XMLHttpRequest interface and the fetch() API.
With HttpClient, #angular/common/http provides a simplified API for HTTP functionality for use with Angular applications, building on top of the XMLHttpRequest interface exposed by browsers. Additional benefits of HttpClient include testability support, strong typing of request and response objects, request and response interceptor support, and better error handling via apis based on Observables.

Phonegap/Cordova and Couchbase Mobile/server

I'm creating my mobile app using phonegap.
I decided to use Couchbase to store datas; but I can't figure out if I must have to use Couchbase mobile or I can connect my app (javascript) directly with couchbase server, and how to 'query' my .net app.
I have downloaded the couchbase server on my system, but how to connect it with my app?
Can I use N1QL to 'query' the server with .NET also using phonegap? (because couchbase mobile doesn't support n1ql).
I could just call a rest web service done with .NET or maybe JAVA but so is it needed to add couchbase mobile to the app?
This is the query of C# couchbase mobile documentation:
var document = database.CreateDocument();
var properties = new Dictionary<string, object>()
{
{"type", "list"},
{"title", "title"},
{"created_at", DateTime.UtcNow.ToString ("o")},
{"owner", "profile:" + userId},
{"members", new List<string>()}
};
var rev = document.PutProperties(properties);
Debug.Assert(rev != null);
how i Call it?
This is a query in Server documentation (the previous was in mobile):
var doc = new Document<dynamic>{ Id = "document_id", Content = new {Some="value"} };
var result = bucket.Insert(doc);
Console.WriteLine(JsonConvert.SerializeObject(result.Document));
why they are different?
This is the function to connect the server to phonegap:
var DB_NAME = 'todo';
function initRESTClient(url) {
var client = new SwaggerClient({
spec: window.spec,
usePromise: true,
})
.then(function (client) {
client.setHost(url);
if (device.platform == 'android') {
var encodedCredentials = "Basic " + window.btoa(url.split('/')[1].split('#')[0]);
client.clientAuthorizations.add("auth", new SwaggerClient.ApiKeyAuthorization('Authorization', encodedCredentials, 'header'));
}
client.server.get_all_dbs()
.then(function (res) {
var dbs = res.obj;
if (dbs.indexOf(DB_NAME) == -1) {
return client.database.put_db({db: DB_NAME});
}
return client.database.get_db({db: DB_NAME});
})
.then(function (res) {
return client.document.post({db: DB_NAME, body: {title: 'Couchbase Mobile', sdk: 'PhoneGap'}});
})
.then(function (res) {
console.log('Document ID :: ' + res.obj.id);
})
.catch(function (err) {
console.log(err);
});
});
}
sorry if I'm a bit confused but I need some high level clarify to get started coding.
At a high level: you need Couchbase mobile on the device and Couchbase Server on server (cloud or on premise). To push/pull data between mobile and server you need the Couchbase Sync Gateway running (cloud or on premise). More information is available over at the Couchbase Mobile Portal for Developers.
With regards to your question as to why the .Net version of mobile and server queries are different-
The Mobile version calls into Couchbase Lite which is the embedded NoSQL database for mobile client platforms. The database is embedded in your mobile/desktop client and it syncs periodically with the Couchbase Server in the cloud via the sync gateway. So you would typically implement this in your Windows mobile app. You can also implement this in your desktop client application.
The server version - In this case, you would use the .Net SDK that queries against the Couchbase Server. You would implement this in your .Net web service app in your backend. You can implement your backend web service in any supported language including Java.
If you are considering Phonegap, you may want to refer to this tutorial. This integrates with Couchbase Lite using a swagger client- there isn't a native JS API hence the swagger based client. The Couchbase Lite syncs with the Couchbase Server via the Sync Gateway.

Firebase Auth + Own Api

is it possible to use only the firebase auth and then create an own api with own database?
So I write an REST API which uses the firebase token to authentificate.
Thanks!
It depends on the technology that you will be using for the backend API. There is a Firebase Admin SDK, that is aimed at Java, Python and Node developers, but I think the functionality that you are looking for is only available in the Node SDK (although I believe that there are workarounds for this).
The way this works is that after your user signs in on the client side, they can request a token using firebase.auth().currentUser.getIdToken() which can then be passed to your backend which can then be verified, see the below example for how it could be done using Node and Restify.
const server = restify.createServer({});
server.use(validateJwt);
function validateJwt(req, res, next) {
if(!req.headers.token){
//reject
}
admin.auth().verifyIdToken(req.headers.token).then(decodedToken=>{
console.log(`token for user ${decodedToken.sub} valid`);
admin.auth().getUser(decodedToken.sub).then(user=>{
console.log(`fetched user ${user.email}`);
next();
}).catch(err=>{
res.send(500, 'the user with the ID does not exist in firebase');
})
}).catch(err=>{
console.log(`token validation failed: ${err}`);
res.send(401, 'authentication failed')});
}
I believe you should be able to do this, by using Firebase to authorise the user and then allow read access to a link securely stored for authenticated users only. This could then link to the database, if this is what you mean. I'd assume you may have already started here, but this is where to start Understand Firebase Realtime Database Rules

Connection between nativescript and MongoDB (mongoose)

I am new in mobile development world and right now trying to understand few basic things.
I did a simple login nativescript app and from backend side did a login logic with mongoose (MongoDb) and express. But now I don't know how to proceed... How do I connect between backend and app?
Thank you in advance,
Emil
You need to expose an API from your backend, I'll assume you have done this (or can find this out - it's very well documented).
So from the client {N} you will need to access the API, calling whichever end-points you need. If you were using a JWT type approach, you should use the http module in nativescript, which might look something like this:
var http = require("http");
var result;
http.request({
url: "https://myBackend.org/api/post",
method: "POST",
headers: { "Content-Type": "application/json" },
content: JSON.stringify({ username: "ValueOne", password: "ValueTwo" })
}).then(function (response) {
result = response.content.toJSON();
console.log(result); //result.message would have the clients auth token
}, function (e) {
// console.log("Error occurred " + e);
});
You could then store the token (in persistent storage with the application-settings module) and add it to the header of any request to a different API endpoint to interact with your backend as an authenticated user.
Alternatively, you can use one of the cloud backend SDKs, e.g. Azure Mobile Services or Firebase which make your life much easier.