Have a problem.
Has someone integrated gRPC web client with Redux-Toolkit RTK query?
You can use libraries that offer you api functions that you have to call with queryFn instead of query.
...
myQuery: builder.query({
async queryFn(arg){
try {
const result = await myApi.someFunction()
return { data: result }
} catch (e) {
return { error: e }
}
}
})
Related
I start to use RTK query and try to update headers with new access tokens but found it's hard to update the access in state. More specifically, there is no way to access dispatch inside prepareHeaders. Only getState is exposed.
createApi({
reducerPath: 'baseApi',
baseQuery: fetchBaseQuery({
baseUrl: "/",
prepareHeaders: (headers, { getState } ) => {
const { token, expiration } = getState().auth
if (expiration > new Date()) {
if (token) {
headers.set('authorization', `Bearer ${token}`)
}
} else {
// if token expired, get a new token
try {
const result = await fetch("/token_store")
//dispatch(setNewToken(result)) ---> how to use dispatch here?
} catch (err) {
console.log("something goes wrong.")
}
}
return headers
}),
endpoints: () => ({}),
});
You should definitely not do that in prepareHeaders - there is a reason why there is no dispatch available there.
For something like that, you would wrap your baseQuery.
There are some examples of wrapping the basequery here in the documentation
I define axios like below
$axios.onResponse((response) => {
if (response.data.status == 500}
return Promise.reject(response)
}
})
$axios.onError((err) => {
console.log(err)
})
and in fetch i call
async fetch () {
await this.$axios.$get('myapi')
}
but i get error like
RangeError
Maximum call stack size exceeded
I try to reject a success response to error but it not working in ssr. How to fix that thank.
Generally, using try-catch statements are preferred over event handlers (where appropriate).
Try something like this:
async fetch() {
try {
const response = await this.$axios.$get('myapi');
if (response.data.status == 500) {
throw new Error("Some error message");
} else {
// Success action here
}
} catch(err) {
console.log(err);
}
}
Is there any particular reason you're returning a rejected Promise when you get a 500 error? Is there any reason not to throw a generalized error message instead?
I use nestjs and psql and I want upload files and save the url in the database . when I run the api , data save on db but it doesn’t return any response .
this is my service:
async uploadFiles(files){
if (!files) {
throw new HttpException(
{
errorCode: UploadApplyOppErrorEnum.FileIsNotValid,
message: UploadApplyOppMsgEnum.FileIsNotValid,
},
HttpStatus.UNPROCESSABLE_ENTITY,
);
}
const filedata = OrderFilesData(files);
return filedata.map(async(filePath) => {
let orderFile = new OrderFile();
orderFile.fileUrl = filePath.fileUrl;
orderFile.type = filePath.fileType;
try {
let result = await this.orderFileRepository.save(orderFile);
return await result
} catch (error) {
throw new BadRequestException(error.detail);
}
});
}
and this is my controller
#UploadOrderFilesDec()
#Post('upload')
uploadFiles(#UploadedFiles() files){
return this.ordersService.uploadFiles(files);
}
You can't return an array of async methods without using Promise.all(), otherwise the promises haven't resolved yet. You can either use return Promise.all(fileData.map(asyncFileMappingFunction)) or you can use a regular for loop and await over the results.
According to the .native() documentation, the way to use .native() query for sails-mongo is :
Pet.native(function(err, collection) {
if (err) return res.serverError(err);
collection.find({}, {
name: true
}).toArray(function (err, results) {
if (err) return res.serverError(err);
return res.ok(results);
});
});
How can I avoid callback here and use promises instead. Note that I have to use aggregate queries, so have to use .native()
As mentioned here Open bootstrap.js in config and monkey patch all methods with promise like this
module.exports.bootstrap = function(cb) {
var Promise = require('bluebird');
Object.keys(sails.models).forEach(function (key) {
if (sails.models[key].query) {
sails.models[key].query = Promise.promisify(sails.models[key].query);
}
});
cb(); };
On the bonus side you get to use the latest version of bluebird with all models. Hope it helps
Using $http I can catch errors like 401 easily:
$http({method: 'GET', url: 'http://localhost/Blog/posts/index.json'}).
success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
if(status == 401)
{
alert('not auth.');
}
$scope.posts = {};
});
But how can I do something similar when using services instead. This is how my current service looks:
myModule.factory('Post', function($resource){
return $resource('http://localhost/Blog/posts/index.json', {}, {
index: {method:'GET', params:{}, isArray:true}
});
});
(Yes, I'm just learning angular).
SOLUTION (thanks to Nitish Kumar and all the contributors)
In the Post controller I was calling the service like this:
function PhoneListCtrl($scope, Post) {
$scope.posts = Post.query();
}
//PhoneListCtrl.$inject = ['$scope', 'Post'];
As suggested by the selected answer, now I'm calling it like this and it works:
function PhoneListCtrl($scope, Post) {
Post.query({},
//When it works
function(data){
$scope.posts = data;
},
//When it fails
function(error){
alert(error.status);
});
}
//PhoneListCtrl.$inject = ['$scope', 'Post'];
in controller call Post like .
Post.index({},
function success(data) {
$scope.posts = data;
},
function err(error) {
if(error.status == 401)
{
alert('not auth.');
}
$scope.posts = {};
}
);
Resources return promises just like http. Simply hook into the error resolution:
Post.get(...).then(function(){
//successful things happen here
}, function(){
//errorful things happen here
});
AngularJS Failed Resource GET
$http is a service just like $resource is a service.
myModule.factory('Post', function($resource){
return $http({method: 'GET', url: 'http://localhost/Blog/posts/index.json'});
});
This will return the promise. You can also use a promise inside your factory and chain that so your factory (service) does all of the error handling for you.