2023-03-14 13:18:55 +00:00
|
|
|
/**
|
|
|
|
* Copyright (c) HashiCorp, Inc.
|
2023-08-11 13:12:13 +00:00
|
|
|
* SPDX-License-Identifier: BUSL-1.1
|
2023-03-14 13:18:55 +00:00
|
|
|
*/
|
|
|
|
|
2022-09-15 08:43:17 +00:00
|
|
|
export default function (P = Promise) {
|
|
|
|
return function (source, listeners) {
|
2019-02-21 10:36:15 +00:00
|
|
|
let current;
|
|
|
|
if (typeof source.getCurrentEvent === 'function') {
|
|
|
|
current = source.getCurrentEvent();
|
|
|
|
}
|
|
|
|
if (current != null) {
|
|
|
|
// immediately resolve if we have previous cached data
|
2022-09-15 08:43:17 +00:00
|
|
|
return P.resolve(current.data).then(function (cached) {
|
2019-06-20 08:35:30 +00:00
|
|
|
source.open();
|
2019-02-21 10:36:15 +00:00
|
|
|
return cached;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
// if we have no previously cached data, listen for the first response
|
2022-09-15 08:43:17 +00:00
|
|
|
return new P(function (resolve, reject) {
|
2019-02-21 10:36:15 +00:00
|
|
|
// close, cleanup and reject if we get an error
|
2022-09-15 08:43:17 +00:00
|
|
|
listeners.add(source, 'error', function (e) {
|
2019-02-21 10:36:15 +00:00
|
|
|
listeners.remove();
|
|
|
|
e.target.close();
|
|
|
|
reject(e.error);
|
|
|
|
});
|
|
|
|
// ...or cleanup and respond with the first lot of data
|
2022-09-15 08:43:17 +00:00
|
|
|
listeners.add(source, 'message', function (e) {
|
2019-02-21 10:36:15 +00:00
|
|
|
listeners.remove();
|
|
|
|
resolve(e.data);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|