Superagent request is undefined - superagent

In version 3 of Superagent I was able to set a variable to the superagent request, like this:
const mySuperagent = superagent
.get(getURL)
.end(function (err, res) {})
And use mySuperagent elsewhere.
But I've updated Superagent to version 7.0.2 and now mySuperagent is 'undefined'.
Does anyone know what has changed because I can't figure it out?

Related

Post request redux thunk

I have GET requests and normally when those succeeded I save data in store, but for POST requests I need to know if it succeeded or not, in order to execute some code (show a message and redirect), the docu says you can use an isLoading variable, but it just says if the service is working but not if it succeeded, if I try to create a new success variable in the store, it will be turned on forever after the request and I don't need that either. I tried returning a promise from the action creator and handle response directly inside the component but it looks like the same to call axios there instead of using redux.
My action creator looks like this:
export function createProject(userId, projectName) {
return function (dispatch) {
dispatch({ type: projectsActions.START_CREATE_PROJECT });
return ProjectsService.createProject(userId, projectName).then(() => {
dispatch({ type: projectsActions.SUCCESS_CREATE_PROJECT });
}).catch((error) => {
dispatch({ type: projectsActions.ERROR_CREATE_PROJECT });
throw error;
});
}
}
I understand where your doubts are coming from, it doesn't seem appropriate to have a field on your Redux store only to know the success of a one-time request.
If you only need to make a post request and only care about it's result once, the simplest way to do it is to use state in the component making the request. Component-level state is easily manageable and gets removed from memory when the component is unmounted, but on the other hand you may want to have a single source of truth for your app. You have to make a choice, but your Redux implementation is correct.

Firebase callable + express?

With functions.https.onRequest(app); it was possible to use express right away.
I'm wondering if it's possible to use functions.https.onCall(...) together with express in the same way?
onCall(...) seem to have a different signature but maybe there is still a way to keep using express while working with onCall(...) functions?
No, it's not possible. Callable functions force your endpoint to use a certain path, a certain type of input (JSON via POST) and a certain type of output (also JSON). Express wouldn't really help you out, given the constraints of how callables work. You can read about all the callable protocol details in the documentation. You can see that callables abstract away all of the details of the request and response, which you would normally work with when using Express.
What does work however is using onRequest and calling that... then you can use express like normal and have the simplicity of firebase callable on the client side...
then you can do your authorization like normal. For example with the following middleware:
export const createFirebaseAuth = () => (req: express.Request, res: express.Response, next: express.NextFunction) => {
console.log('Time: ', Date.now());
const token = req.header('Authorization');
if (!token) {
res.status(400);
res.send('Authtoken must be sent with a request');
return;
}
admin
.auth()
.verifyIdToken(token.replace('Bearer ', ''))
.then((v) => {
req.user = v;
next();
})
.catch((error) => {
res.status(401);
res.send(error.message);
res.end();
});
}

AngularFire httpsCallable Object(...) is not a function

I want to call a httpsCallable function in my Ionic 3 app. I am attempting to follow these docs: https://firebase.google.com/docs/functions/callable
I tried:
const newGame = (firebase as any).functions().httpsCallable('findCreateGame');
newGame({}).then(function(result) {
console.log("In here.");
});
Which resulted in:
ERROR TypeError: WEBPACK_IMPORTED_MODULE_5_firebase_functions.functions is not a function
I also tried the newly implemented wrapper in angularfire:
const newGame = this.afFunctions.httpsCallable('findCreateGame');
newGame({}).then(function(result) {
console.log("In here.");
});
ERROR TypeError: Object(...) is not a function
Does anyone have any experience with this yet? Here is the pull request to add the functionality if that helps at all. https://github.com/angular/angularfire2/pull/1532
EDIT---
This code actually calls the Cloud function even though it throws the same 'Not a function' error:
const newGame = this.afFunctions.httpsCallable('findCreateGame');
newGame();
I'm not sure how else to call the function, even though newGame is an object and not a function reference.
The Object(...) is not a function is thrown because you're running rxjs 5, rather than 6.
If you upgrade, the function will perform as expected.
See the rxjs migration doc for more details on the changes between 5 and 6.
In your first example make sure you are importing import 'firebase/functions' in the ts file you're calling the function.

How to access custom response values from a page script?

This might sound like a silly question but I have really tried everything I could to figure it out. I am creating a variable and adding it to my response object in custom Express server file like so:
server.get('*', (req, res) => {
res.locals.user = req.user || null;
handle(req, res);
});
Now I want to access this res.locals.user object from all of my pages, i.e. index.js, about.js, etc., in order to keep a tab on the active session's user credentials. It's got to be possible some way, right?
P.S.: Reading some thread on the NextJS Github page, I tried accessing it from my props object as this.props.user but it keeps returning null even when a server-side console.log shows non-null values.
The res object is available on the server as a parameter to getInitialProps. So, with the server code you have above, you can do
static async getInitialProps({res}) {
return { user: res.locals.user }
}
to make it available as this.props.user.

How Firebase Cloud functions handle HTTP post method?

I have created Firebase Cloud Functions app,
I created function with https.onRequest.
and get data with req.body but there is not data there.
Can Firebase Cloud Functions can handle HTTP POST method?
This is my sample code:-
var functions = require('firebase-functions');
exports.testPost = functions.https.onRequest((req, res) => {
console.log(req.body);
});
I tested by postman with POST method but didn't show result in Firebase log.
Functions built on Firebase can also use Express.js routers for handling GET/POST/PUT/DELETE, etc... is fully supported by Google, and is the recommended way to implement these types of functions.
More documentation can be found here:
https://firebase.google.com/docs/functions/http-events
Here's a working example built on Node.js
const functions = require('firebase-functions');
const express = require('express');
const cors = require('cors');
const app = express();
// Automatically allow cross-origin requests
app.use(cors({ origin: true }));
app.get('/hello', (req, res) => {
res.end("Received GET request!");
});
app.post('/hello', (req, res) => {
res.end("Received POST request!");
});
// Expose Express API as a single Cloud Function:
exports.widgets = functions.https.onRequest(app);
Then, run firebase deploy, and that should compile your code and create the new "widgets" function. Note: You can rename widgets to anything you want. Ultimately, it will generate a URL for calling the function.
I am planning to do the same thing. What I reckon the approach should be is to check the request.method in the function body. A probable approach can be:
if (request.method != "POST") {
respond.status(400).send("I am not happy");
return;
}
// handle the post request
Here's some reference to the details regarding what the request object holds: https://firebase.google.com/docs/functions/http-events
Firebase functions support GET, POST, PUT, DELETE, and OPTIONS method, and you can check what kind of methods that trigger your function.
// Check for POST request
if(request.method !== "POST"){
res.status(400).send('Please send a POST request');
return;
}
Then to get data from POST request (for example JSON type) will be in the header of your request.
const postData = request.body;
// for instance
const format = req.body.format;
// query string params
let format = req.query.format;
Maybe your project hasn't been setup to communicate with your firebase database. Try the following from your terminal:
npm install -g firebase-tools
Then inside your project folder, run the following and login using your credentials
firebase login
Then
firebase init functions
This will create a folder with index.js, package.json and node_modules
If you are using Postman correctly the rest of your code should work.

Resources