How to use rxjs ajax operator instead of axios in my react project? - ajax

I am new to rxjs and want to know how to handle this use case.
This is axios promise, how to convert it so that it uses rxjs's ajax operator
export const onLogin = ({ username, password }) =>
axios({
method: "post",
url: O_TOKEN_URL,
data: querystring.stringify({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
grant_type: "password",
username,
password
}),
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
This is my action,
export const onSubmit = payload => ({
type: FETCH_USER,
payload // payload contains username & password
});
This is my epic for now,
export const loginEpic = action$ =>
action$
.ofType(FETCH_USER)
// somehow import onLogin from above and resolve it
// then, dispatch FETCH_USER_FULFILLED
.do(
payload => console.log(payload.username, payload.password)
// i am able to console these username and password
)
.mapTo(() => null);
I want to resolve onLogin function somehow, when FETCH_USER is dispatched, using rxjs's ajax operator.
And, I want onLogin function, which returns promise/observable, to be set up in different file so that I can keep track of all the ajax requests
These are the packages,
"redux-observable": "^0.18.0",
"rxjs": "^5.5.10",
Could you also point me to a documentation that covers this and various use case for post, put ... requests? I couldn't find any.

The ajax config object is fairly similar to what you already have. I'm assuming the data property for the axios request is the request body.
import {ajax} from 'rxjs/observable/dom/ajax';
export const onLogin = ({ username, password }) =>
ajax({
method: "POST",
url: O_TOKEN_URL,
body: JSON.stringify({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
grant_type: "password",
username,
password
}),
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
Your epic would look something like this:
export const loginEpic = action$ =>
action$
.ofType(FETCH_USER)
.mergeMap(action =>
onLogin(action.payload)
// map will be called when the request succeeded
// so we dispatch the success action here.
.map((ajaxResponse) => fetchUserFulfilled())
// catch will be called if the request failed
// so we dispatch the error action here.
// Note that you must return an observable from this function.
// For more advanced cases, you can also apply retry logic here.
.catch((ajaxError, source$) => Observable.of(fetchUserFailed()))
);
Where fetchUserFulfilled and fetchUserFailed are action creator functions.
There does not seem to be much documentation of the RxJS 5 ajax method yet. Here are the links to the official v5 docs for the AjaxRequest, AjaxResponse and AjaxError. The AjaxError object in particular has 0 information so far (at the time of this answer) so you will need to rely on the source code if you need to use this object for more than a trigger to tell the user that something went wrong. The ajax source code is here.

Related

How to return HTTP response body from Cypress custom command?

I am trying to write a custom Cypress command that sends a POST request to an endpoint, & I then want to store the response body in my test.
Here is what the response body looks like in Postman:
Here is my custom command in cypress/support/commands.js, for simplicity, I've removed the request body values:
Cypress.Commands.add('createStudent', (email) => {
cy.request({
method: `POST`,
url: `myUrl`,
body: {}
}).then((resp) => {
return resp
});
});
Here is the code in my spec file:
let response = cy.createStudent(email);
cy.log(response)
However, when I run the code I get back the below object rather than the response body:
Can someone please tell me where I am going wrong, & what changes are required to return the actual HTTP response body?
If you look at the console message, there's a type $Chainer shown which is a wrapper object around the result you actually want (response).
The Chainer is fundamental to Cypress being able to retry queries that fail initially but may succeed within a timeout period (usually 4 seconds).
But it means you can't use the return value. Instead you need to "unwrap" the value using .then().
Cypress.Commands.add('createStudent', (email) => {
cy.request({
method: 'POST',
url: 'myUrl',
body: {...}
})
// The response is put on the "chain" upon exit of the custom command
// You need nothing else here to get the raw response
})
cy.createStudent().then(response => {
cy.log(response)
});
You can add a step to extract details from the response, like
Cypress.Commands.add('createStudent', (email) => {
cy.request({
method: 'POST',
url: 'myUrl',
body: {...}
})
.then(response => {
expect(response.success).to.eq(true) // check expected response is good
return response.body.id // pass on just the id
})
})
cy.createStudent().then(id => {
cy.log(id)
});
If you'll only ever be using the value in a Cypress chain, you could simply alias the command.
Cypress.Commands.add('createStudent', (email) => {
cy.request({
method: `POST`,
url: `myUrl`,
body: {}
}).as('student');
});
...
cy.createStudent();
cy.get('#student').then((response) => {
cy.log(response.body) // assuming you'd want to log the response body.
});
// OR
cy.get('#student').its('body').should('eq', { foo: 'bar' });
// the above example doesn't work with logging, but I'm guessing you don't _just_ want to log the response
If you may need the variable at other times outside of a Cypress chain, you could always stash the variable in Cypress.env().
Cypress.Commands.add('createStudent', (email) => {
cy.request({
method: `POST`,
url: `myUrl`,
body: {}
}).then((res) => {
Cypress.env('student', res);
});
});
...
cy.createStudent().then(() => {
cy.get('foo').should('have.text', Cypress.env('student').body.foo);
});
// key point is referencing the entire response by `Cypress.env('student')`

Vuejs Laravel Passport - what should I do if access token is expired?

I am using Vuejs SPA with Laravel API as backend. I successfully got the personal access token and store in localStorage and Vuex state like below.
token: localStorage.getItem('token') || '',
expiresAt: localStorage.getItem('expiresAt') || '',
I use the access token every time I send axios request to laravel api. Every thing works well. However, initially the token was set to 1 year expiration so when I develop I didn't care about token being expired and today suddenly I thought what is going to happen if token expired. So I set token expiry to 10 seconds in laravel AuthServiceProvier.php.
Passport::personalAccessTokensExpireIn(Carbon::now()->addSecond(10));
and then I logged in and after 10 seconds, every requests stopped working because the token was expired and got 401 unauthorised error.
In this case, how can I know if the token is expired? I would like to redirect the user to login page if token is expired when the user is using the website.
Be as user friendly as possible. Rather than waiting until the token expires, receiving a 401 error response, and then redirecting, set up a token verification check on the mounted hook of your main SPA instance and have it make a ajax call to e.g. /validatePersonalToken on the server, then do something like this in your routes or controller.
Route::get('/validatePersonalToken', function () {
return ['message' => 'is valid'];
})->middleware('auth:api');
This should return "error": "Unauthenticated" if the token is not valid. This way the user will be directed to authenticate before continuing to use the app and submitting data and then potentially losing work (like submitting a form) which is not very user friendly.
You could potentially do this on a component by component basis rather than the main instance by using a Vue Mixin. This would work better for very short lived tokens that might expire while the app is being used. Put the check in the mounted() hook of the mixin and then use that mixin in any component that makes api calls so that the check is run when that component is mounted. https://v2.vuejs.org/v2/guide/mixins.html
This is what I do. Axios will throw error if the response code is 4xx or 5xx, and then I add an if to check if response status is 401, then redirect to login page.
export default {
methods: {
loadData () {
axios
.request({
method: 'get',
url: 'https://mysite/api/route',
})
.then(response => {
// assign response.data to a variable
})
.catch(error => {
if (error.response.status === 401) {
this.$router.replace({name: 'login'})
}
})
}
}
}
But if you do it like this, you have to copy paste the catch on all axios call inside your programs.
The way I did it is to put the code above to a javascript files api.js, import the class to main.js, and assign it to Vue.prototype.$api
import api from './api'
Object.defineProperty(Vue.prototype, '$api', { value: api })
So that in my component, I just call the axios like this.
this.$api.GET(url, params)
.then(response => {
// do something
})
The error is handled on api.js.
This is my full api.js
import Vue from 'vue'
import axios from 'axios'
import router from '#/router'
let config = {
baseURL : process.env.VUE_APP_BASE_API,
timeout : 30000,
headers : {
Accept : 'application/json',
'Content-Type' : 'application/json',
},
}
const GET = (url, params) => REQUEST({ method: 'get', url, params })
const POST = (url, data) => REQUEST({ method: 'post', url, data })
const PUT = (url, data) => REQUEST({ method: 'put', url, data })
const PATCH = (url, data) => REQUEST({ method: 'patch', url, data })
const DELETE = url => REQUEST({ method: 'delete', url })
const REQUEST = conf => {
conf = { ...conf, ...config }
conf = setAccessTokenHeader(conf)
return new Promise((resolve, reject) => {
axios
.request(conf)
.then(response => {
resolve(response.data)
})
.catch(error => {
outputError(error)
reject(error)
})
})
}
function setAccessTokenHeader (config) {
const access_token = Vue.cookie.get('access_token')
if (access_token) {
config.headers.Authorization = 'Bearer ' + access_token
}
return config
}
/* https://github.com/axios/axios#handling-errors */
function outputError (error) {
if (error.response) {
/**
* The request was made and the server responded with a
* status code that falls out of the range of 2xx
*/
if (error.response.status === 401) {
router.replace({ name: 'login' })
return
}
else {
/* other response status such as 403, 404, 422, etc */
}
}
else if (error.request) {
/**
* The request was made but no response was received
* `error.request` is an instance of XMLHttpRequest in the browser
* and an instance of http.ClientRequest in node.js
*/
}
else {
/* Something happened in setting up the request that triggered an Error */
}
}
export default {
GET,
POST,
DELETE,
PUT,
PATCH,
REQUEST,
}
You could use an interceptor with axios. Catch the 401s and clear the local storage when you do then redirect user to appropriate page.

Can fetch be a substitute for AJAX?

I am wondering if it is possible to do in fetch all the things you can do in traditional ajax?
Because I'm having a problem with a simple login authentication using express. I want to send a response like Login error if the username/password is incorrect, or to redirect the user to the homepage if both is correct, to the client without refreshing the page.
I understand that you can do this in AJAX, but is it possible to do it in fetch also?
I tried using express js and sending a response through a json, but I can't figure out how to handle the response without refreshing the page.
I tried doing it like this in the express server
//if valid
res.json({
isValid: true
})
//if invalid
res.json({
isValid: false
})
And in the client side, specifically in the login page, I have this javascript that handles the submitting of the information
fetch('https://localhost:3000/auth', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
username,
password
})
})
.then(response => response.json())
.then(data => {
//I understand that in this part, you can handle the response, but the problem is, I don't know how.
}
})
.catch(console.log)
You are SO close! You've got the fetch, then you've parsed it with response.json, so the next thing is the .then(). In that, you have the JSON object being passed into a param you've named data. All you need to do is check if that has the isValid property!
fetch('https://localhost:3000/auth', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
username,
password
})
})
.then(response => response.json())
.then(data => {
if(data.isValid){
// Do something with a valid user. Redirect or whatever.
} else {
// Here, isValid is not set, or is false.
// Send them packing!
}
}
})
.catch(err => console.error("I died: ", err) );
ALSO, take a look at the .catch() block -- in the event of an error, that catches an Error thrown by either the fetch(), or a then(). So you need to add a parameter for the error, and a function body to handle that. I've edited my code sample to demonstrate.
Won't actually run here, but it's formatted all pretty.

Difficulty creating a functional Angular2 post

I'm trying to send a post request to another service (a Spring application), an authentication, but I'm having trouble constructing a functional Angular2 post request at all. I'm using this video for reference, which is pretty new, so I assume the information still valid. I'm also able to execute a get request with no problems.
Here's my post request:
export class LogIn {
authUser: string;
authPass: string;
token: any;
constructor(private _http:Http){}
onSubmit() {
var header = new Headers()
var json = JSON.stringify({ user: this.authUser, password: this.authPass })
var params2 = 'user=' + this.authUser + '&password=' + this.authPass
var params = "json=" + json
header.append('Content-Type', 'application/x-www-form-urlencoded')
this._http.post("http://validate.jsontest.com", params, {
headers: header
}).map(res => res.json())
.subscribe(
data => this.token = JSON.stringify(data),
err => console.error(err),
() => console.log('done')
);
console.log(this.token);
}
}
The info is being correctly taken from a form, I tested it a couple of times to make sure. I am also using two different ways to build the json (params and params2). When I try to send the request to http://validate.jsontest.com, the console prints undefined where this.token should be. When I try to send the request to the Spring application, I get an error on that side:
Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
Does anyone know what I'm doing wrong?
In fact you need to use the GET method to do that:
var json = JSON.stringify({
user: this.authUser, password: this.authPass
});
var params = new URLSearchParams();
params.set('json', json);
this._http.get("http://validate.jsontest.com", {
search: params
}).map(res => res.json());
See this plunkr: http://plnkr.co/edit/fAHPp49vFZJ8OuPC1043?p=preview.

RxJS calling second operation when first is successful

I'm using Angular2 and rxjs.
I have an operation called login(). This will use a http.post request to send the authentication details to the server and will then receive a token back.
It needs to read the result and if the token is received successfully it will do some operations to validate the token and decode it, and if all of this is OK then it will send the username from the token to the server with a http.get and retrieve the user's details.
I would like all of the above to be returned as one Observable, but I'm scratching my head as to how two operations that should occur one after the other should be structured using the RxJS way.
I don't think subscribing to the first operation and then calling the second operation inside the first is the "right" way, because then how do you capture a failure in the first one.
Something like this?
this.http.post('http://localhost/auth/token', creds, {
headers: headers
})
.map(res => res.json())
.do(
// validate token
// decode token
)
.thenDo(
// get user details
this.http.get(url, options)
.map(res => res.json())
.do(
//save user and token in localStorage
)
)
i dont know much about Rxjs do and thenDo function but yes you can do like this
this.http.post('http://localhost/auth/token', creds, {
headers: headers
})
.map(res => {
return [{status: res.status , json: res.json()}]
})
.subscribe(res=>{
if(res[0].status == 200){ // do you action depends on status code you got assuming 200 for OK response
this.validateToken() // Validate your token here in some method named as validateToken
this.decodeToken() // decode token here in this method
this.getUserDetail() //if everything worked fine call your another get request in another method
}
},
err => {
console.log(err, err.status) //catch your error here
})
getUserDetail(){
// make http get request for user detail and saveing into locastroage
}
Using flatMap is a good way to chain operations that each return a new Promise or Observable. Each time we need to map over a function that returns a Promise or Observable, we can use flatMap to construct a stream that emits the resolved data. Here we construct an Observable of user data, and finally we can subscribe to it (to save to localstorage, etc).
I've assumed your validation code is just some function that returns a Promise or Observable.
const options = { headers };
const user$ = this.http.post('http://localhost/auth/token', creds, options)
.map(res => res.json())
.flatMap(validationFunctionThatReturnsAPromise)
.flatMap(authResponse => {
// get user details
return this.http.get(url, options).map(res => res.json());
});
user$.subscribe(user => /** do something with the user data **/);

Resources