Skip to content

Commit

Permalink
Add "new" action to BankAccount
Browse files Browse the repository at this point in the history
  • Loading branch information
Pierstoval committed Sep 22, 2024
1 parent c504ae2 commit ee07e06
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
17 changes: 10 additions & 7 deletions src/lib/crud/cruds/BankAccountsCrud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
CrudDefinition,
Edit,
List,
New,
TextField,
UrlAction,
type RequestParameters,
Expand All @@ -17,7 +18,7 @@ import {
getBankAccounts,
updateBankAccount
} from '$lib/db/bank_accounts';
import type BankAccount from '$lib/entities/BankAccount';
import BankAccount from '$lib/entities/BankAccount';
import { goto } from '$app/navigation';
import { success } from '$lib/utils/message';

Expand All @@ -34,8 +35,11 @@ export default new CrudDefinition<BankAccount>({
// minStateLoadingTimeMs: 0,

operations: [
new List([...baseFields], [new UrlAction('Edit', '/crud/bank-accounts/edit')]),
new Edit(baseFields)
new List([...baseFields], [new UrlAction('Edit', '/crud/bank-accounts/edit')], {
globalActions: [new UrlAction('New', '/crud/bank-accounts/new')]
}),
new Edit(baseFields),
new New(baseFields),
],

stateProvider: new CallbackStateProvider<BankAccount>(
Expand Down Expand Up @@ -67,11 +71,10 @@ export default new CrudDefinition<BankAccount>({
if (!data) {
throw new Error('Cannot create new object: empty data.');
}
if (Array.isArray(data)) {
throw new Error('Cannot update data as array for this action.');
}

return createBankAccount(data);
await createBankAccount(BankAccount.fromObject(data));
success('Success!');
await goto('/crud/bank-accounts/list');
}

if (operation.name === 'edit') {
Expand Down
8 changes: 8 additions & 0 deletions src/lib/entities/BankAccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ export default class BankAccount implements Entity {
});
}

static fromObject(object: {[key: string]: any}): BankAccount {
if ((object.id && isNaN(object.id)) || !object.name || !object.slug || !object.currency) {
throw new Error('Invalid object: cannot create a BankAccount.');
}

return new BankAccount(Number(object.id)||0, object.name, object.slug, object.currency);
}

public setId(id: number) {
if (!id) {
throw new Error('Cannot set an empty ID on an object.');
Expand Down

0 comments on commit ee07e06

Please sign in to comment.