1.0.2 • Published 5 years ago

@magno/sweetalert2-guards v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
5 years ago

SweetAlert2 Guards are a simple, opinionated solution to elegantly wrap your JavaScript methods execution in alerts, without having to mix UI and logic code.

It can be used in any framework or custom solution that uses classes and class methods (Angular, React, Vue, etc.) – because of a language limitation, decorators can't be used on simple functions yet.

//  Here's a simple example (the class is omitted):

import { guard, Confirm, ErrorStrategy } from '@sweetalert2/guards';

@Confirm(file => ({
    title: `Delete ${file}?`,
    text: `You won't be able to revert this!`,
    [guard.errorStrategy]: ErrorStrategy.validationError,
    [guard.onSuccess]: () => void swal('Deleted!', `${file} has been deleted`, 'success')
}))
public async deleteFile(file: string) {

  const response = await fetch(`/api/files/${file}`, { method: 'delete' });

    if (!response.ok) {
        throw new Error(`An error occurred: ${response.statusText}`);
    }

}

✅ Now, every code that calls this method, may it be external code, Angular template, React JSX, etc. will transparently trigger a confirmation modal.

Resulting in:



📦 Installation & Requirements

Install @magno/sweetalert2-guards and sweetalert2 via the npm registry:

npm install --save sweetalert2 @magno/sweetalert2-guards

x TypeScript: Guards is written in TypeScript – type definitions are bundled in the package.

👉 Using Angular and liking declarative approaches? See also ngx-sweetalert2.

👉 Before posting an issue, please check that the problem isn't on SweetAlert's side.

🔗 API

@Alert() Guard

This decorator is the simplest one. It will display an alert before your method executes, show a loading indicator when it's executing, and that's all.

{
    showLoaderOnConfirm: true,
    allowOutsideClick: () => !swal.isLoading(),
    allowEscapeKey: () => !swal.isLoading()
}
@Alert({
    title: 'Downloading the Internet',
    text: 'This operation will take a long time. Please be patient.',
    type: 'warning'
})
public downloadTheInternet() {
    // If the following service returns a Promise,
    // the alert will show a loading indicator.
    return this.myInternerService.download('http://*');
}

@Confirm() Guard

This decorator will show a confirmation dialog with Confirm and Cancel buttons. The user may choose to execute the decorated method or not.

{
    type: 'question',
    showCancelButton: true,
    showLoaderOnConfirm: true,
    allowOutsideClick: () => !swal.isLoading(),
    allowEscapeKey: () => !swal.isLoading()
}
@Confirm({
    title: 'Close account?',
    text: 'This will definitely close you account and you won\'t be able to login anymore.',
    type: 'warning'
})
public closeMyAccount() {
    return this.userService.closeAccount();
}

@Loader() Guard

This decorator will execute the decorated method as soon as it's called, showing a loading indicator while the method is executing.

{
    showConfirmButton: false,
    showLoaderOnConfirm: true,
    allowOutsideClick: () => !swal.isLoading(),
    allowEscapeKey: () => !swal.isLoading(),
    onBeforeOpen: swal.clickConfirm
}
@Loader({
    title: 'Please wait',
    text: 'This may take a few seconds...'
})
public async syncDataFromApi() {
    const datas = await this.api.getDatas();

    this.apiCache.store(datas);
}

[guard.*] options

[guard.invokeStrategy]

[guard.errorStrategy]

[guard.onDismiss]

[guard.onError]

[guard.onSuccess]

🍲 Recipes

❔ Q0: How to change the modal's parameters depending on the method's arguments?

❔ Q1: How to pass the SweetAlert2 modal result to the method?

❔ Q2: How to modify the arguments passed to the method?

See Q1.

❔ Q3: When I click "Cancel", I want the function to return a result, not throw an exception

❔ Q4: I want to return a "placeholder" result when the modal is dismissed

See Q3.

❔ Q5: I want to show an error or success modal when the method has terminated

❔ Q6: Can I use synchronous code in the methods?