Skip to content

Commit

Permalink
debt(sequelize): move attributes to declare
Browse files Browse the repository at this point in the history
  • Loading branch information
Betree committed May 25, 2022
1 parent e3b9e48 commit 39645b2
Show file tree
Hide file tree
Showing 24 changed files with 276 additions and 347 deletions.
2 changes: 1 addition & 1 deletion .babelrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{
"presets": [
"@babel/preset-typescript",
[
"@babel/preset-env",
{
Expand All @@ -11,6 +10,7 @@
]
],
"plugins": [
["@babel/plugin-transform-typescript", { "allowDeclareFields": true }],
"add-module-exports",
"lodash",
"@babel/plugin-proposal-class-properties",
Expand Down
16 changes: 5 additions & 11 deletions docs/adding-new-models.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ module.exports = {
Example: `server/models/MyTable.ts`

```ts
import restoreSequelizeAttributesOnClass from '../lib/restore-sequelize-attributes-on-class';
import sequelize, { DataTypes, Model } from '../lib/sequelize';

// Define all attributes for the model
Expand All @@ -70,16 +69,11 @@ interface MyTableCreateAttributes {
}

class MyTable extends Model<MyTableAttributes, MyTableCreateAttributes> implements MyTableAttributes {
id: number;
MyCollectiveId: number;
createdAt: Date;
updatedAt: Date;
deletedAt: Date;

constructor(...args) {
super(...args);
restoreSequelizeAttributesOnClass(new.target, this);
}
declare id: number;
declare MyCollectiveId: number;
declare createdAt: Date;
declare updatedAt: Date;
declare deletedAt: Date;
}

MyTable.init(
Expand Down
98 changes: 45 additions & 53 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
"@babel/plugin-proposal-class-properties": "7.17.12",
"@babel/plugin-transform-async-to-generator": "7.17.12",
"@babel/preset-env": "7.18.0",
"@babel/preset-typescript": "7.17.12",
"@hyperwatch/hyperwatch": "3.8.2",
"@node-oauth/oauth2-server": "4.1.1",
"@octokit/auth-oauth-app": "4.3.1",
Expand Down Expand Up @@ -129,6 +128,7 @@
"devDependencies": {
"@babel/cli": "^7.16.0",
"@babel/eslint-parser": "^7.16.0",
"@babel/plugin-transform-typescript": "^7.17.12",
"@babel/register": "^7.16.0",
"@types/lodash": "^4.14.171",
"@types/mocha": "^9.0.0",
Expand Down
31 changes: 18 additions & 13 deletions server/graphql/common/expenses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import { canUseFeature } from '../../lib/user-permissions';
import { formatCurrency } from '../../lib/utils';
import models, { sequelize } from '../../models';
import { ExpenseAttachedFile } from '../../models/ExpenseAttachedFile';
import { ExpenseItem } from '../../models/ExpenseItem';
import { ExpenseItem, ItemsDiff } from '../../models/ExpenseItem';
import { PayoutMethodTypes } from '../../models/PayoutMethod';
import paymentProviders from '../../paymentProviders';
import {
Expand Down Expand Up @@ -951,15 +951,13 @@ export const changesRequireStatusUpdate = (
export const getItemsChanges = async (
existingItems: ExpenseItem[],
expenseData: ExpenseData,
): Promise<
[boolean, Record<string, unknown>[], [Record<string, unknown>[], ExpenseItem[], Record<string, unknown>[]]]
> => {
): Promise<[boolean, ItemsDiff]> => {
if (expenseData.items) {
const itemsDiff = models.ExpenseItem.diffDBEntries(existingItems, expenseData.items);
const hasItemChanges = flatten(<unknown[]>itemsDiff).length > 0;
return [hasItemChanges, expenseData.items, itemsDiff];
return [hasItemChanges, itemsDiff];
} else {
return [false, [], [[], [], []]];
return [false, [[], [], []]];
}
};

Expand Down Expand Up @@ -1017,7 +1015,7 @@ export async function editExpense(
],
});

const [hasItemChanges, itemsData, itemsDiff] = await getItemsChanges(expense.items, expenseData);
const [hasItemChanges, itemsDiff] = await getItemsChanges(expense.items, expenseData);
const taxes = expenseData.tax || expense.data?.taxes || [];
const expenseType = expenseData.type || expense.type;
checkTaxes(expense.collective, expense.collective.host, expenseType, taxes);
Expand Down Expand Up @@ -1113,11 +1111,13 @@ export async function editExpense(

// Update items
if (hasItemChanges) {
checkExpenseItems({ ...expense.dataValues, ...cleanExpenseData }, itemsData, taxes);
const [newItemsData, oldItems, itemsToUpdate] = itemsDiff;
const simulatedItems = ExpenseItem.simulateItemsDiff(expense.items, itemsDiff);
checkExpenseItems({ ...expense.dataValues, ...cleanExpenseData }, simulatedItems, taxes);
// TODO: Move the code below to ExpenseItem.applyItemsDiff
const [newItemsData, removedItems, itemsToUpdate] = itemsDiff;
await Promise.all(<Promise<void>[]>[
// Delete
...oldItems.map(item => {
...removedItems.map(item => {
return item.destroy({ transaction: t });
}),
// Create
Expand All @@ -1129,6 +1129,8 @@ export async function editExpense(
return models.ExpenseItem.updateFromData(itemData, t);
}),
]);

expense.items = await expense.getItems({ transaction: t });
}

// Update expense
Expand All @@ -1149,10 +1151,13 @@ export async function editExpense(
);

await createAttachedFiles(expense, newAttachedFiles, remoteUser, t);
await Promise.all(removedAttachedFiles.map((file: ExpenseAttachedFile) => file.destroy()));
await Promise.all(removedAttachedFiles.map((file: ExpenseAttachedFile) => file.destroy({ transaction: t })));
await Promise.all(
updatedAttachedFiles.map((file: Record<string, unknown>) =>
models.ExpenseAttachedFile.update({ url: file.url }, { where: { id: file.id, ExpenseId: expense.id } }),
models.ExpenseAttachedFile.update(
{ url: file.url },
{ where: { id: file.id, ExpenseId: expense.id }, transaction: t },
),
),
);
}
Expand All @@ -1167,7 +1172,7 @@ export async function editExpense(
const updatedExpenseProps = {
...cleanExpenseData,
data: !expense.data ? null : cloneDeep(expense.data),
amount: computeTotalAmountForExpense(expenseData.items || expense.items, taxes),
amount: computeTotalAmountForExpense(expense.items, taxes),
lastEditedById: remoteUser.id,
incurredAt: expenseData.incurredAt || new Date(),
status,
Expand Down
23 changes: 0 additions & 23 deletions server/lib/restore-sequelize-attributes-on-class.ts

This file was deleted.

16 changes: 5 additions & 11 deletions server/models/CurrencyExchangeRate.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,14 @@
import restoreSequelizeAttributesOnClass from '../lib/restore-sequelize-attributes-on-class';
import sequelize, { DataTypes, Model } from '../lib/sequelize';

/**
* Sequelize model to represent an CurrencyExchangeRate, linked to the `CurrencyExchangeRates` table.
*/
export class CurrencyExchangeRate extends Model {
public readonly id!: number;
public rate!: number;
public from!: string;
public to!: string;
public createdAt!: Date;

constructor(...args) {
super(...args);
restoreSequelizeAttributesOnClass(new.target, this);
}
public declare readonly id: number;
public declare rate: number;
public declare from: string;
public declare to: string;
public declare createdAt: Date;

static getMany(
fromCurrency: string,
Expand Down

0 comments on commit 39645b2

Please sign in to comment.