Skip to content

Commit 4963d3f

Browse files
authored
chore: Migrate session methods to async await (#76)
* chore: Migrate session methods to async await * fix: move response initialization to within try block
1 parent a9e7e78 commit 4963d3f

File tree

1 file changed

+69
-98
lines changed

1 file changed

+69
-98
lines changed

source/session.ts

Lines changed: 69 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -521,7 +521,7 @@ export class Session {
521521
* @param {string} options.decodeDatesAsIso - Return dates as ISO strings instead of moment objects
522522
*
523523
*/
524-
call<T = ActionResponse>(
524+
async call<T = ActionResponse>(
525525
operations: operation.Operation[],
526526
{
527527
abortController,
@@ -531,21 +531,16 @@ export class Session {
531531
decodeDatesAsIso = false,
532532
}: CallOptions = {}
533533
): Promise<IsTuple<T> extends true ? T : T[]> {
534+
await this.initializing;
534535
const url = `${this.serverUrl}${this.apiEndpoint}`;
535536

536-
// Delay call until session is initialized if initialization is in
537-
// progress.
538-
let request = new Promise<void>((resolve) => {
539-
if (this.initializing && !this.initialized) {
540-
this.initializing.then(() => {
541-
resolve();
542-
});
543-
} else {
544-
resolve();
545-
}
546-
})
547-
.then(() =>
548-
fetch(url, {
537+
try {
538+
// Delay call until session is initialized if initialization is in
539+
// progress.
540+
541+
let fetchResponse;
542+
try {
543+
fetchResponse = await fetch(url, {
549544
method: "post",
550545
credentials: "include",
551546
headers: {
@@ -560,54 +555,45 @@ export class Session {
560555
} as HeadersInit,
561556
body: this.encodeOperations(operations),
562557
signal: abortController ? abortController.signal : signal,
563-
})
564-
)
565-
.catch((reason) => {
566-
logger.warn("Failed to perform request. ", reason);
558+
});
559+
} catch (reason) {
560+
if (reason instanceof Error) {
561+
throw this.getErrorFromResponse({
562+
exception: "NetworkError",
563+
content: reason.message,
564+
});
565+
}
566+
throw new Error("Unknown error");
567+
}
568+
569+
const response = await fetchResponse.json();
570+
571+
if (response.exception) {
572+
throw this.getErrorFromResponse(response);
573+
}
574+
575+
return this.decode(response, {}, decodeDatesAsIso);
576+
} catch (reason) {
577+
logger.warn("Failed to perform request. ", reason);
578+
579+
if (reason instanceof Error) {
567580
if (reason.name === "AbortError") {
568-
return Promise.resolve<ResponseError>({
581+
throw this.getErrorFromResponse({
569582
exception: "AbortError",
570583
content: reason.message,
571584
});
572585
}
573-
return Promise.resolve<ResponseError>({
574-
exception: "NetworkError",
575-
content: reason.message,
576-
});
577-
})
578-
.then((response) => {
579-
if ("json" in response) {
580-
return (response.json && response.json()) || response;
581-
}
582-
return response;
583-
})
584-
.then((data) => {
585-
if (this.initialized) {
586-
return this.decode(data, {}, decodeDatesAsIso);
587-
}
588586

589-
return data;
590-
})
591-
// Catch badly formatted responses
592-
.catch((reason) => {
593587
logger.warn("Server reported error in unexpected format. ", reason);
594-
return Promise.resolve<ResponseError>({
588+
throw this.getErrorFromResponse({
595589
exception: "MalformedResponseError",
596590
content: reason.message,
597591
error: reason,
598592
});
599-
})
600-
// Reject promise on API exception.
601-
.then((response) => {
602-
if (response.exception) {
603-
return Promise.reject<ResponseError>(
604-
this.getErrorFromResponse(response as ResponseError)
605-
);
606-
}
607-
return Promise.resolve(response);
608-
});
593+
}
594+
}
609595

610-
return request;
596+
throw new Error("Unknown error");
611597
}
612598

613599
/**
@@ -744,17 +730,16 @@ export class Session {
744730
* @return {Promise} Promise which will be resolved with an object
745731
* containing action, data and metadata
746732
*/
747-
query<T extends Data = Data>(expression: string, options: QueryOptions = {}) {
733+
async query<T extends Data = Data>(
734+
expression: string,
735+
options: QueryOptions = {}
736+
) {
748737
logger.debug("Query", expression);
749-
const queryOperation = operation.query(expression);
750-
let request = this.call<[QueryResponse<T>]>([queryOperation], options).then(
751-
(responses) => {
752-
const response = responses[0];
753-
return response;
754-
}
738+
const responses = await this.call<[QueryResponse<T>]>(
739+
[operation.query(expression)],
740+
options
755741
);
756-
757-
return request;
742+
return responses[0];
758743
}
759744

760745
/**
@@ -774,7 +759,7 @@ export class Session {
774759
* @return {Promise} Promise which will be resolved with an object
775760
* containing data and metadata
776761
*/
777-
search<T extends Data = Data>(
762+
async search<T extends Data = Data>(
778763
{
779764
expression,
780765
entityType,
@@ -792,22 +777,19 @@ export class Session {
792777
objectTypeIds,
793778
});
794779

795-
const searchOperation = operation.search({
796-
expression,
797-
entityType,
798-
terms,
799-
contextId,
800-
objectTypeIds,
801-
});
802-
let request = this.call<[SearchResponse<T>]>(
803-
[searchOperation],
780+
const responses = await this.call<[SearchResponse<T>]>(
781+
[
782+
operation.search({
783+
expression,
784+
entityType,
785+
terms,
786+
contextId,
787+
objectTypeIds,
788+
}),
789+
],
804790
options
805-
).then((responses) => {
806-
const response = responses[0];
807-
return response;
808-
});
809-
810-
return request;
791+
);
792+
return responses[0];
811793
}
812794

813795
/**
@@ -821,22 +803,18 @@ export class Session {
821803
* @param {object} options.decodeDatesAsIso - Decode dates as ISO strings instead of moment objects
822804
* @return {Promise} Promise which will be resolved with the response.
823805
*/
824-
create<T extends Data = Data>(
806+
async create<T extends Data = Data>(
825807
entityType: string,
826808
data: T,
827809
options: MutationOptions = {}
828810
) {
829811
logger.debug("Create", entityType, data, options);
830812

831-
let request = this.call<[CreateResponse<T>]>(
813+
const responses = await this.call<[CreateResponse<T>]>(
832814
[operation.create(entityType, data)],
833815
options
834-
).then((responses) => {
835-
const response = responses[0];
836-
return response;
837-
});
838-
839-
return request;
816+
);
817+
return responses[0];
840818
}
841819

842820
/**
@@ -851,23 +829,19 @@ export class Session {
851829
* @param {object} options.decodeDatesAsIso - Decode dates as ISO strings instead of moment objects
852830
* @return {Promise} Promise resolved with the response.
853831
*/
854-
update<T extends Data = Data>(
832+
async update<T extends Data = Data>(
855833
type: string,
856834
keys: string[],
857835
data: T,
858836
options: MutationOptions = {}
859837
) {
860838
logger.debug("Update", type, keys, data, options);
861839

862-
const request = this.call<[UpdateResponse<T>]>(
840+
const responses = await this.call<[UpdateResponse<T>]>(
863841
[operation.update(type, keys, data)],
864842
options
865-
).then((responses) => {
866-
const response = responses[0];
867-
return response;
868-
});
869-
870-
return request;
843+
);
844+
return responses[0];
871845
}
872846

873847
/**
@@ -881,18 +855,15 @@ export class Session {
881855
* @param {object} options.decodeDatesAsIso - Decode dates as ISO strings instead of moment objects
882856
* @return {Promise} Promise resolved with the response.
883857
*/
884-
delete(type: string, keys: string[], options: MutationOptions = {}) {
858+
async delete(type: string, keys: string[], options: MutationOptions = {}) {
885859
logger.debug("Delete", type, keys, options);
886860

887-
let request = this.call<[DeleteResponse]>(
861+
const responses = await this.call<[DeleteResponse]>(
888862
[operation.delete(type, keys)],
889863
options
890-
).then((responses) => {
891-
const response = responses[0];
892-
return response;
893-
});
864+
);
894865

895-
return request;
866+
return responses[0];
896867
}
897868

898869
/**

0 commit comments

Comments
 (0)