2023-04-10 15:36:59 +00:00
|
|
|
/**
|
|
|
|
* Copyright (c) HashiCorp, Inc.
|
|
|
|
* SPDX-License-Identifier: MPL-2.0
|
|
|
|
*/
|
|
|
|
|
2021-12-08 19:26:25 +00:00
|
|
|
import { action } from '@ember/object';
|
|
|
|
import Component from '@glimmer/component';
|
|
|
|
import { tracked } from '@glimmer/tracking';
|
|
|
|
import { task } from 'ember-concurrency';
|
2022-03-08 17:28:36 +00:00
|
|
|
import { schedule } from '@ember/runloop';
|
2021-12-08 19:26:25 +00:00
|
|
|
|
|
|
|
const noOp = () => undefined;
|
|
|
|
|
|
|
|
export default class Trigger extends Component {
|
|
|
|
@tracked error = null;
|
|
|
|
@tracked result = null;
|
|
|
|
|
|
|
|
get isBusy() {
|
|
|
|
return this.triggerTask.isRunning;
|
|
|
|
}
|
|
|
|
|
|
|
|
get isIdle() {
|
|
|
|
return this.triggerTask.isIdle;
|
|
|
|
}
|
|
|
|
|
|
|
|
get isSuccess() {
|
2021-12-14 17:56:03 +00:00
|
|
|
return this.triggerTask.last?.isSuccessful;
|
2021-12-08 19:26:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
get isError() {
|
2021-12-14 17:56:03 +00:00
|
|
|
return !!this.error;
|
2021-12-08 19:26:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
get fns() {
|
|
|
|
return {
|
|
|
|
do: this.onTrigger,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
get onError() {
|
|
|
|
return this.args.onError ?? noOp;
|
|
|
|
}
|
|
|
|
|
|
|
|
get onSuccess() {
|
|
|
|
return this.args.onSuccess ?? noOp;
|
|
|
|
}
|
|
|
|
|
|
|
|
get data() {
|
|
|
|
const { isBusy, isIdle, isSuccess, isError, result } = this;
|
|
|
|
return { isBusy, isIdle, isSuccess, isError, result };
|
|
|
|
}
|
|
|
|
|
2021-12-14 17:56:03 +00:00
|
|
|
_reset() {
|
|
|
|
this.result = null;
|
|
|
|
this.error = null;
|
|
|
|
}
|
|
|
|
|
2022-01-20 15:39:02 +00:00
|
|
|
@task(function* () {
|
2021-12-14 17:56:03 +00:00
|
|
|
this._reset();
|
2021-12-08 19:26:25 +00:00
|
|
|
try {
|
|
|
|
this.result = yield this.args.do();
|
|
|
|
this.onSuccess(this.result);
|
|
|
|
} catch (e) {
|
2021-12-14 17:56:03 +00:00
|
|
|
this.error = { Error: e };
|
2021-12-08 19:26:25 +00:00
|
|
|
this.onError(this.error);
|
|
|
|
}
|
|
|
|
})
|
|
|
|
triggerTask;
|
|
|
|
|
|
|
|
@action
|
|
|
|
onTrigger() {
|
2022-03-08 17:28:36 +00:00
|
|
|
schedule('actions', () => {
|
|
|
|
this.triggerTask.perform();
|
|
|
|
});
|
2021-12-08 19:26:25 +00:00
|
|
|
}
|
|
|
|
}
|