Skip to content

Commit

Permalink
feat(tRPC): validate exchange account credentials on CREATE/UPDATE
Browse files Browse the repository at this point in the history
  • Loading branch information
bludnic committed Jul 25, 2024
1 parent 96cb88e commit efb765c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { xprisma } from "@opentrader/db";
import { checkExchangeCredentials } from "../../../../utils/exchange-account.js";
import { eventBus } from "../../../../event-bus.js";
import type { Context } from "../../../../utils/context.js";
import type { TCreateExchangeAccountInputSchema } from "./schema.js";
Expand All @@ -11,7 +12,7 @@ type Options = {
};

export async function createExchangeAccount({ input, ctx }: Options) {
const exchangeAccount = await xprisma.exchangeAccount.create({
let exchangeAccount = await xprisma.exchangeAccount.create({
data: {
...input,
owner: {
Expand All @@ -21,6 +22,17 @@ export async function createExchangeAccount({ input, ctx }: Options) {
},
},
});

const { valid } = await checkExchangeCredentials(exchangeAccount);
exchangeAccount = await xprisma.exchangeAccount.update({
where: {
id: exchangeAccount.id,
},
data: {
expired: !valid,
},
});

eventBus.exchangeAccountCreated(exchangeAccount);

return exchangeAccount;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { xprisma } from "@opentrader/db";
import { checkExchangeCredentials } from "../../../../utils/exchange-account.js";
import type { Context } from "../../../../utils/context.js";
import type { TUpdateExchangeAccountInputSchema } from "./schema.js";
import { eventBus } from "../../../../event-bus.js";
Expand All @@ -11,14 +12,27 @@ type Options = {
};

export async function updateExchangeAccount({ input, ctx }: Options) {
const exchangeAccount = await xprisma.exchangeAccount.update({
let exchangeAccount = await xprisma.exchangeAccount.update({
where: {
id: input.id,
ownerId: ctx.user.id,
},
data: input.body,
});

// It's important to trigger the event before checking the credentials
// to invalidate the cache of ExchangeProvider.
eventBus.exchangeAccountUpdated(exchangeAccount);

const { valid } = await checkExchangeCredentials(exchangeAccount);
exchangeAccount = await xprisma.exchangeAccount.update({
where: {
id: exchangeAccount.id,
},
data: {
expired: !valid,
},
});

return exchangeAccount;
}

0 comments on commit efb765c

Please sign in to comment.