How can i return rejected from async-await? - async-await

I would like to return rejected, when fetch request is fail. How can i reject async await?
class FetchUrl {
static async getJson(api) {
try {
const response = await fetch(api);
if (response.ok) {
const questions = await response.json();
return questions;
}
} catch (error) {
throw new Error("Request Failed!");
}
}
}
FetchUrl.getJson(this.api).then((resolved) => {
console.log(resolved)
// this sampe of code is executing even fetch is rejected.. what can i do
to avoid it?
}, rejected => {
console.log(rejected)
})
}

Related

Graphql - universal permission guards

I am trying to implement permission guards in a graphql backend using apollo server. The following code works:
Resolvers
const Notification = require('../../database/models/notifications');
const Task = require('../../database/models/tasks');
notification: combineResolvers(isNotificationOwner, async (_, { id }) => {
try {
const notification = await Notification.findById(id);
return notification;
} catch (error) {
throw error;
}
})
task: combineResolvers(isTaskOwner, async (_, { id }) => {
try {
const task = await Task.findById(id);
return task;
} catch (error) {
throw error;
}
})
Resolver Middleware (permission guards)
const Notification = require('../../database/models/notifications');
const Task = require('../../database/models/tasks');
// userId is the id of the logged in user retrieved from the context
module.exports.isNotificationOwner = async (_, { id }, { userId }) => {
try {
const notification = await Notification.findById(id);
if (notification.user.toString() !== userId) {
throw new ForbiddenError('You are not the owner');
}
return skip;
} catch (error) {
throw error;
}
}
module.exports.isTaskOwner = async (_, { id }, { userId }) => {
try {
const task = await Task.findById(id);
if (task.user.toString() !== userId) {
throw new ForbiddenError('You are not the owner');
}
return skip;
} catch (error) {
throw error;
}
}
Going on like this will create a lot of duplicate code and does not feel very DRY. Therefore, I am trying to create a more universal solution, to no evail so far.
What I tried:
Resolvers
const Notification = require('../../database/models/notifications');
const Task = require('../../database/models/tasks');
notification: combineResolvers(isOwner, async (_, { id }) => {
try {
const notification = await Notification.findById(id);
return notification;
} catch (error) {
throw error;
}
})
task: combineResolvers(isOwner, async (_, { id }) => {
try {
const task = await Task.findById(id);
return task;
} catch (error) {
throw error;
}
})
Resolver Middleware
const Notification = require('../../database/models/notifications');
const Task = require('../../database/models/tasks');
module.exports.isOwner = async (_, { id, collection }, { userId }) => {
try {
const document = await collection.findById(id);
if (document.user.toString() !== userId) {
throw new ForbiddenError('You are not the owner');
}
return skip;
} catch (error) {
throw error;
}
}
I am unable to pass a collection name as an argument to the middleware resolver.
I would be tremendously thankful for any kind of help!
Based off your code, it seems like you're looking for making isOwner a higher-order function, so that you can pass in the collection, and it returns the curried method.
module.exports.isOwner = (collection) => {
return async (_, { id }, { userId }) => {
try {
const document = await collection.findById(id);
if (document.user.toString() !== userId) {
throw new ForbiddenError('You are not the owner');
}
return skip;
} catch (error) {
throw error;
}
}
}
Usage:
const resolvers = {
Query: {
task: combineResolvers(isOwner(Task), async (_, { id }) => {
try {
const task = await Task.findById(id);
return task;
} catch (error) {
throw error;
}
})
},
};

Data does not save on database after implementing validation

I have problem with my validation where after I implement it saveProduct() function, the data that I want to store does not add or update to the database. Also, I shared the product service file, because someone said also have to pass the 'this.productForm.value' inside service file. but I'm not quite sure how.
Below is the code: details.page.ts
ngOnInit() {
this.productForm = this.fb.group({
productName: new FormControl('', Validators.compose([
Validators.required,
])),
productDecs: new FormControl('', Validators.compose([
Validators.required,
])),
});
}
async saveProduct() {
await this.presentLoading();
this.product.userId = this.authService.getAuth().currentUser.uid;
if (this.productId) {
try {
console.log('product update');
console.log(this.productForm.value);
await this.productService.updateProduct(this.productId, this.productForm.value);
await this.loading.dismiss();
this.navCtrl.navigateBack('/vendor-tabs/home-vendor');
} catch (error) {
console.log('product dont update');
this.presentToast('Error trying to save');
this.loading.dismiss();
}
} else {
this.product.createdAt = new Date().getTime();
try {
console.log(this.productForm.value);
console.log('product add');
await this.productService.addProduct(this.productForm.value);
await this.loading.dismiss();
this.navCtrl.navigateBack('/vendor-tabs/home-vendor');
} catch (error) {
console.log('product dont add');
this.presentToast('Error trying to save');
this.loading.dismiss();
}
}
}
Below is the code for product.service.ts
addProduct(product: Product) {
return this.productsCollection.add(product);
}
getProduct(id: string) {
return this.productsCollection.doc<Product>(id).valueChanges();
}
updateProduct(id: string, product: Product) {
return this.productsCollection.doc<Product>(id).update(product);
}
deleteProduct(id: string) {
return this.productsCollection.doc(id).delete();
}

Set the sequence of execution of asynchronous dispatch (redux\redux-saga)

I need to perform an asynchronous request. To do this, I'm debating a preloader, then I make a request, then I want to stop the preloader. The console should have: "show loader, load-app, hide loader", and output "show loader, hide loader, loading-app". How to save a sequence of calls?
How set the sequence of execution of asynchronous dispatch (redux\redux-saga)?
import { showLoader, hideLoader } from '../../reducer1'
import { authorizeToken } from '../reducer2'
async componentDidMount() {
const { dispatch } = this.props
const tokenLS = localStorage.getItem('token')
await dispatch(showLoader()); //show loader
await dispatch(authorizeToken(tokenLS)); // async request
await dispatch(hideLoader()); //hide loader
}
}
This code for Loader
import * as act from './actions'
const initialState = {
loadingPage: false
}
export const showLoader = () => {
console.log('show loader')
document.body.classList.add('loading-app')
return { type: act.startLoading }
}
export const hideLoader = () => {
console.log('hide loader')
document.body.classList.remove('loading-app')
return { type: act.finishLoading }
}
export default function loading(state = initialState, action) {
switch (action.type) {
case act.startLoading:
return { ...state, loadingPage: true }
case act.finishLoading:
return { ...state, loadingPage: false }
default:
return state
}
}
This code for async request:
function* authorizeWithToken({ payload: { token } }) {
try {
const { token:userToken } = yield call(authApi.authUserFromToken, token)
yield put({ type: AUTH_SUCCESS, payload: { token: userToken } })
yield console.log('end request')
} catch (error) {
throw new Error(`error request with token ${token}`)
}
}
export function* authorizeSaga() {
yield takeLatest(AUTH_REQUEST, authorize)
}
export function* authorizeWithTokenSaga() {
yield takeLatest(AUTH_REQUEST_TOKEN, authorizeWithToken)
}
This is reducer:
export const authorizeToken = (token) => ({
type: AUTH_REQUEST_TOKEN,
payload: {token}
})
I think there's some misunderstanding here. Your componentDidMount function does not need to by async. redux-saga enables you to move all async actions into sagas and out of the components. That way your components are easier to manage. I would change your componentDidMount to dispatch a single action and let your saga handle all the logic. Try changing it to this:
import { authorizeToken } from '../reducer2'
componentDidMount() {
const { dispatch } = this.props
const tokenLS = localStorage.getItem('token')
dispatch(authorizeToken(tokenLS)); // async request
}
Now in your saga, try this:
import { showLoader, hideLoader } from '../../reducer1'
function* authorizeWithToken({ payload: { token } }) {
try {
yield put(showLoader());
const { token:userToken } = yield call(authApi.authUserFromToken, token)
yield put({ type: AUTH_SUCCESS, payload: { token: userToken } })
yield put(hideLoader())
} catch (error) {
throw new Error(`error request with token ${token}`)
}
}
Now your saga will be in charge of displaying the loader, fetching the data, and hiding the loader. In that order.

Call multiple ajax and wait for result Angular2

I have problem with my Angular. I have this functions:
private callUserInfo(): any {
this.isLoading = true;
return this._ajaxService.getService('/system/ping')
.map(
result => {
this.userId =
result.participant.substring(result.participant.indexOf('#'));
this.isLoading = false;
}
)
.catch(error => {
return Observable.throw(error);
});
}
public loadUserData(userName: string): any {
this.isLoading = true;
return this._ajaxService.getService('/User/' + userName)
.map(
result => {
const data = result[0];
this.user = new User(
data.id,
data.contacts[0].email,
data.name,
data.surname,
data.address.street,
data.address.city,
data.address.state,
data.address.country,
data.address.postCode,
data.address.timeZone);
this.isLoading = false;
})
.catch(error => {
return Observable.throw(error);
});
}
public getUser(): any {
if (this.user == null) {
this.callUserInfo().subscribe(() => {
this.loadUserData(this.userId).subscribe(() => {
return this.user;
});
});
} else {
return this.user;
}
}
In my component I call this service functions like this (auth service is service with functions defined up):
constructor(private _auth: AuthService) {
this.user = _auth.getUser();
}
But it stills return null (because Ajax calls are not finished?) Can someone explain me, how to call this two calls (first is system/ping service and based on return (userId) I need to call second ajax call (/user/id). After this two calls I have defined user in my service and I can return it to other components. Can someone expllain me, what am i doing wrong, or how I can do it better? I´m using newest version of angular.
P.S. Get service is from my wrapper service:
getService(url: string): Observable<any> {
return this.http
.get(this.base + url, this.options)
.map(this.extractData)
.catch(this.handleError);
}
You are not returning anything in case this.user==null
Change your function as following:
userObservabel=new BehaviourSubject(null);
public getUser(): any {
if (this.user == null) {
this.callUserInfo().subscribe(() => {
this.loadUserData(this.userId).subscribe(() => {
this.userObservabel.next(this.user);
});
});
return this.userObservabel.asObservable();
} else {
return this.userObservabel.asObservable();
}
}
and then you need to subscribe it
constructor(private _auth: AuthService) {
_auth.getUser().subscribe(user => this.user = user);
}
You need to call the second service in the subscribe or in the map method i.e. the Observable has returned a promise and that is resolved. Once that is resolved u should call your chained service.
A sample snipped from my POC might help you
this._accountListService.getAccountsFromBE().subscribe(
response => {
this.response = response;
this._accountListService.getAccountSorting().subscribe(
response => {
this.acctSort = response;
if (response.prodCode) {
this._accountListService.getAccountOrder().subscribe(
response => {
this.acctOrder = response;
this.response = this.setAccountOrder(this.response);
this.response.sort(this.myComparator);
this.acctFlag = true;
if (this.prodDesc) {
this.loader = false;
this.accountDetl = this.response[0];
this.accountDetl.entCdeDesc = this.prodDesc[this.accountDetl.entProdCatCde];
}
},
err => console.log(err)
);
}
},
err => console.log(err)
);
},
err => console.log(err)
);

Await and Async callbacks hell

I want to make the UserDataGenerator class works like a traditional SYNC class.
My expectation is that userData.outputStructure can give me the data prepared.
let userData = new UserDataGenerator(dslContent)
userData.outputStructure
getFieldDescribe(this.inputStructure.tableName, field) is a ASYNC call which invokes Axios.get
Below is my current progress but it's still not waiting for the data ready when I print out the userData.outputStructure
export default class UserDataGenerator {
inputStructure = null;
outputStructure = null;
fieldDescribeRecords = [];
constructor(dslContent) {
this.outputStructure = Object.assign({}, dslContent, initSections)
process()
}
async process() {
await this.processSectionList()
return this.outputStructure
}
async processSectionList() {
await this.inputStructure.sections.map(section => {
this.outputStructure.sections.push(this.processSection(section));
})
}
async processSection(section) {
let outputSection = {
name: null,
fields: []
}
let outputFields = await section.fields.map(async(inputField) => {
return await this._processField(inputField).catch(e => {
throw new SchemaError(e, this.inputStructure.tableName, inputField)
})
})
outputSection.fields.push(outputFields)
return outputSection
}
async _processField(field) {
let resp = await ai
switch (typeof field) {
case 'string':
let normalizedDescribe = getNormalizedFieldDescribe(resp.data)
return new FieldGenerator(normalizedDescribe, field).outputFieldStructure
}
}
You're trying to await arrays, which doesn't work as you expect. When dealing with arrays of promises, you still need to use Promise.all before you can await it - just like you cannot chain .then on the array.
So your methods should look like this:
async processSectionList() {
const sections = await Promise.all(this.inputStructure.sections.map(section =>
this.processSection(section)
));
this.outputStructure.sections.push(...sections);
}
async processSection(section) {
return {
name: null,
fields: [await Promise.all(section.fields.map(inputField =>
this._processField(inputField).catch(e => {
throw new SchemaError(e, this.inputStructure.tableName, inputField)
})
))]
};
}

Resources