Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 66 additions & 57 deletions lib/actions/user.actions.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
'use server';
"use server";

import { ID, Query } from "node-appwrite";
import { createAdminClient, createSessionClient } from "../appwrite";
import { cookies } from "next/headers";
import { encryptId, extractCustomerIdFromUrl, parseStringify } from "../utils";
import { CountryCode, ProcessorTokenCreateRequest, ProcessorTokenCreateRequestProcessorEnum, Products } from "plaid";

import { plaidClient } from '@/lib/plaid';
import {
CountryCode,
ProcessorTokenCreateRequest,
ProcessorTokenCreateRequestProcessorEnum,
Products,
} from "plaid";

import { plaidClient } from "@/lib/plaid";
import { revalidatePath } from "next/cache";
import { addFundingSource, createDwollaCustomer } from "./dwolla.actions";

Expand All @@ -23,14 +28,14 @@ export const getUserInfo = async ({ userId }: getUserInfoProps) => {
const user = await database.listDocuments(
DATABASE_ID!,
USER_COLLECTION_ID!,
[Query.equal('userId', [userId])]
)
[Query.equal("userId", [userId])]
);

return parseStringify(user.documents[0]);
} catch (error) {
console.log(error)
console.log(error);
}
}
};

export const signIn = async ({ email, password }: signInProps) => {
try {
Expand All @@ -44,37 +49,37 @@ export const signIn = async ({ email, password }: signInProps) => {
secure: true,
});

const user = await getUserInfo({ userId: session.userId })
const user = await getUserInfo({ userId: session.userId });

return parseStringify(user);
} catch (error) {
console.error('Error', error);
console.error("Error", error);
}
}
};

export const signUp = async ({ password, ...userData }: SignUpParams) => {
const { email, firstName, lastName } = userData;

let newUserAccount;

try {
const { account, database } = await createAdminClient();

newUserAccount = await account.create(
ID.unique(),
email,
password,
ID.unique(),
email,
password,
`${firstName} ${lastName}`
);

if(!newUserAccount) throw new Error('Error creating user')
if (!newUserAccount) throw new Error("Error creating user");

const dwollaCustomerUrl = await createDwollaCustomer({
...userData,
type: 'personal'
})
type: "personal",
});

if(!dwollaCustomerUrl) throw new Error('Error creating Dwolla customer')
if (!dwollaCustomerUrl) throw new Error("Error creating Dwolla customer");

const dwollaCustomerId = extractCustomerIdFromUrl(dwollaCustomerUrl);

Expand All @@ -86,9 +91,9 @@ export const signUp = async ({ password, ...userData }: SignUpParams) => {
...userData,
userId: newUserAccount.$id,
dwollaCustomerId,
dwollaCustomerUrl
dwollaCustomerUrl,
}
)
);

const session = await account.createEmailPasswordSession(email, password);

Expand All @@ -101,20 +106,20 @@ export const signUp = async ({ password, ...userData }: SignUpParams) => {

return parseStringify(newUser);
} catch (error) {
console.error('Error', error);
console.error("Error", error);
}
}
};

export async function getLoggedInUser() {
try {
const { account } = await createSessionClient();
const result = await account.get();

const user = await getUserInfo({ userId: result.$id})
const user = await getUserInfo({ userId: result.$id });

return parseStringify(user);
} catch (error) {
console.log(error)
console.log(error);
return null;
}
}
Expand All @@ -123,33 +128,33 @@ export const logoutAccount = async () => {
try {
const { account } = await createSessionClient();

cookies().delete('appwrite-session');
cookies().delete("appwrite-session");

await account.deleteSession('current');
await account.deleteSession("current");
} catch (error) {
return null;
}
}
};

export const createLinkToken = async (user: User) => {
try {
const tokenParams = {
user: {
client_user_id: user.$id
client_user_id: user.$id,
},
client_name: `${user.firstName} ${user.lastName}`,
products: ['auth'] as Products[],
language: 'en',
country_codes: ['US'] as CountryCode[],
}
products: ["auth", "transactions"] as Products[],
language: "en",
country_codes: ["US"] as CountryCode[],
};

const response = await plaidClient.linkTokenCreate(tokenParams);

return parseStringify({ linkToken: response.data.link_token })
return parseStringify({ linkToken: response.data.link_token });
} catch (error) {
console.log(error);
}
}
};

export const createBankAccount = async ({
userId,
Expand All @@ -174,13 +179,13 @@ export const createBankAccount = async ({
fundingSourceUrl,
shareableId,
}
)
);

return parseStringify(bankAccount);
} catch (error) {
console.log(error);
}
}
};

export const exchangePublicToken = async ({
publicToken,
Expand All @@ -194,7 +199,7 @@ export const exchangePublicToken = async ({

const accessToken = response.data.access_token;
const itemId = response.data.item_id;

// Get account information from Plaid using the access token
const accountsResponse = await plaidClient.accountsGet({
access_token: accessToken,
Expand All @@ -209,16 +214,18 @@ export const exchangePublicToken = async ({
processor: "dwolla" as ProcessorTokenCreateRequestProcessorEnum,
};

const processorTokenResponse = await plaidClient.processorTokenCreate(request);
const processorTokenResponse = await plaidClient.processorTokenCreate(
request
);
const processorToken = processorTokenResponse.data.processor_token;

// Create a funding source URL for the account using the Dwolla customer ID, processor token, and bank name
const fundingSourceUrl = await addFundingSource({
// Create a funding source URL for the account using the Dwolla customer ID, processor token, and bank name
const fundingSourceUrl = await addFundingSource({
dwollaCustomerId: user.dwollaCustomerId,
processorToken,
bankName: accountData.name,
});

// If the funding source URL is not created, throw an error
if (!fundingSourceUrl) throw Error;

Comment on lines +223 to 231

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix: throw an Error instance instead of the constructor

throw Error throws the function object, not an Error instance.

-    if (!fundingSourceUrl) throw Error;
+    if (!fundingSourceUrl) throw new Error("Failed to create funding source URL");
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const fundingSourceUrl = await addFundingSource({
dwollaCustomerId: user.dwollaCustomerId,
processorToken,
bankName: accountData.name,
});
// If the funding source URL is not created, throw an error
if (!fundingSourceUrl) throw Error;
const fundingSourceUrl = await addFundingSource({
dwollaCustomerId: user.dwollaCustomerId,
processorToken,
bankName: accountData.name,
});
// If the funding source URL is not created, throw an error
if (!fundingSourceUrl) throw new Error("Failed to create funding source URL");
🤖 Prompt for AI Agents
In lib/actions/user.actions.ts around lines 223 to 231, the code throws the
Error constructor instead of an Error instance. Replace "throw Error" with
"throw new Error()" or "throw new Error('Descriptive message')" to correctly
throw an Error object.

Expand All @@ -242,7 +249,7 @@ export const exchangePublicToken = async ({
} catch (error) {
console.error("An error occurred while creating exchanging token:", error);
}
}
};

export const getBanks = async ({ userId }: getBanksProps) => {
try {
Expand All @@ -251,14 +258,14 @@ export const getBanks = async ({ userId }: getBanksProps) => {
const banks = await database.listDocuments(
DATABASE_ID!,
BANK_COLLECTION_ID!,
[Query.equal('userId', [userId])]
)
[Query.equal("userId", [userId])]
);

return parseStringify(banks.documents);
} catch (error) {
console.log(error)
console.log(error);
}
}
};

export const getBank = async ({ documentId }: getBankProps) => {
try {
Expand All @@ -267,29 +274,31 @@ export const getBank = async ({ documentId }: getBankProps) => {
const bank = await database.listDocuments(
DATABASE_ID!,
BANK_COLLECTION_ID!,
[Query.equal('$id', [documentId])]
)
[Query.equal("$id", [documentId])]
);

return parseStringify(bank.documents[0]);
} catch (error) {
console.log(error)
console.log(error);
}
}
};

export const getBankByAccountId = async ({ accountId }: getBankByAccountIdProps) => {
export const getBankByAccountId = async ({
accountId,
}: getBankByAccountIdProps) => {
try {
const { database } = await createAdminClient();

const bank = await database.listDocuments(
DATABASE_ID!,
BANK_COLLECTION_ID!,
[Query.equal('accountId', [accountId])]
)
[Query.equal("accountId", [accountId])]
);

if(bank.total !== 1) return null;
if (bank.total !== 1) return null;

return parseStringify(bank.documents[0]);
} catch (error) {
console.log(error)
console.log(error);
}
}
};