Reputation: 2644
I have an event that fires calling another service which will create an organization. The organization is returned as an observable. I then use swithMap so I can get the organization id and use it to create an organization user. That response also returns an observable. In the subscribe next the data returned is not the organization, rather it is the organization user object. I want to return the organization, so I somehow need to get the first observable.
return new Promise((resolve, reject) => {
this.organizationController
.send(CREATE_ORGANIZATION, organizationEvent)
.pipe(
switchMap((org) => {
if (org === null) {
reject(new UnprocessableEntityException());
}
const organizationUserEvent: OrganizationUserEventDto = {
dto: {
userId: user.id,
organizationId: org.id,
role: Role.SUPER,
},
};
return this.organizationController.send(
CREATE_ORGANIZATION_USER,
organizationUserEvent,
);
}),
)
.subscribe({
next: (data) => {
resolve(data);
},
error: (e) => {
reject(e);
},
});
});
I tried many things and managed to get this to work with the following changes. As you can see I am simply mapping the second response and returning the data from the first observable instead. I feel like there must be a better way.
return new Promise((resolve, reject) => {
this.organizationController
.send(CREATE_ORGANIZATION, organizationEvent)
.pipe(
mergeMap((org) => {
if (org === null) {
reject(new UnprocessableEntityException());
}
const organizationUserEvent: OrganizationUserEventDto = {
dto: {
userId: user.id,
organizationId: org.id,
role: Role.SUPER,
},
};
return this.organizationController
.send(CREATE_ORGANIZATION_USER, organizationUserEvent)
.pipe(
map(() => {
return { org: org };
}),
);
}),
)
.subscribe({
next: ({ org: org }) => {
resolve(org);
},
error: (e) => {
reject(e);
},
});
});
I also tried using wthLatestFrom with the below arrangment and this caused the first API call to occur twice and did not work.
return new Promise((resolve, reject) => {
const $org = this.organizationController.send(
CREATE_ORGANIZATION,
organizationEvent,
);
$org
.pipe(
mergeMap((org) =>
this.organizationController.send(CREATE_ORGANIZATION_USER, {
userId: user.id,
organizationId: org.id,
role: Role.SUPER,
}),
),
withLatestFrom($org),
)
.subscribe({
next: ([data, org]) => {
resolve(data);
},
error: (e) => {
reject(e);
},
});
});
I appreciate any input. Thank you in advance.
Upvotes: 0
Views: 54