Skip to content

Commit 23c248a

Browse files
service refactor to namespaces
1 parent d8f20d9 commit 23c248a

10 files changed

+80
-90
lines changed

lib/services/account.service.ts

+28-22
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,17 @@ import { AccountLimitError } from './errors';
1414

1515
const config = useRuntimeConfig();
1616

17-
export default class AccountService {
18-
async getAccountById(account_id: number): Promise<AccountWithMembers> {
17+
export namespace AccountService {
18+
export async function getAccountById(
19+
account_id: number
20+
): Promise<AccountWithMembers> {
1921
return prisma_client.account.findFirstOrThrow({
2022
where: { id: account_id },
2123
...accountWithMembers
2224
});
2325
}
2426

25-
async getAccountByJoinPassword(
27+
export async function getAccountByJoinPassword(
2628
join_password: string
2729
): Promise<AccountWithMembers> {
2830
return prisma_client.account.findFirstOrThrow({
@@ -31,14 +33,16 @@ export default class AccountService {
3133
});
3234
}
3335

34-
async getAccountMembers(account_id: number): Promise<MembershipWithUser[]> {
36+
export async function getAccountMembers(
37+
account_id: number
38+
): Promise<MembershipWithUser[]> {
3539
return prisma_client.membership.findMany({
3640
where: { account_id },
3741
...membershipWithUser
3842
});
3943
}
4044

41-
async updateAccountStipeCustomerId(
45+
export async function updateAccountStipeCustomerId(
4246
account_id: number,
4347
stripe_customer_id: string
4448
) {
@@ -50,7 +54,7 @@ export default class AccountService {
5054
});
5155
}
5256

53-
async updateStripeSubscriptionDetailsForAccount(
57+
export async function updateStripeSubscriptionDetailsForAccount(
5458
stripe_customer_id: string,
5559
stripe_subscription_id: string,
5660
current_period_ends: Date,
@@ -93,7 +97,7 @@ export default class AccountService {
9397
}
9498
}
9599

96-
async acceptPendingMembership(
100+
export async function acceptPendingMembership(
97101
account_id: number,
98102
membership_id: number
99103
): Promise<MembershipWithAccount> {
@@ -118,7 +122,7 @@ export default class AccountService {
118122
});
119123
}
120124

121-
async deleteMembership(
125+
export async function deleteMembership(
122126
account_id: number,
123127
membership_id: number
124128
): Promise<MembershipWithAccount> {
@@ -140,7 +144,7 @@ export default class AccountService {
140144
});
141145
}
142146

143-
async joinUserToAccount(
147+
export async function joinUserToAccount(
144148
user_id: number,
145149
account_id: number,
146150
pending: boolean
@@ -179,7 +183,10 @@ export default class AccountService {
179183
});
180184
}
181185

182-
async changeAccountName(account_id: number, new_name: string) {
186+
export async function changeAccountName(
187+
account_id: number,
188+
new_name: string
189+
) {
183190
return prisma_client.account.update({
184191
where: { id: account_id },
185192
data: {
@@ -188,7 +195,7 @@ export default class AccountService {
188195
});
189196
}
190197

191-
async changeAccountPlan(account_id: number, plan_id: number) {
198+
export async function changeAccountPlan(account_id: number, plan_id: number) {
192199
const plan = await prisma_client.plan.findFirstOrThrow({
193200
where: { id: plan_id }
194201
});
@@ -202,7 +209,7 @@ export default class AccountService {
202209
});
203210
}
204211

205-
async rotateJoinPassword(account_id: number) {
212+
export async function rotateJoinPassword(account_id: number) {
206213
const join_password: string = generator.generate({
207214
length: 10,
208215
numbers: true
@@ -217,7 +224,7 @@ export default class AccountService {
217224
// User must already be an ADMIN for the Account
218225
// Existing OWNER memberships are downgraded to ADMIN
219226
// In future, some sort of Billing/Stripe tie in here e.g. changing email details on the Account, not sure.
220-
async claimOwnershipOfAccount(
227+
export async function claimOwnershipOfAccount(
221228
user_id: number,
222229
account_id: number
223230
): Promise<MembershipWithUser[]> {
@@ -278,7 +285,7 @@ export default class AccountService {
278285
}
279286

280287
// Upgrade access of a membership. Cannot use this method to upgrade to or downgrade from OWNER access
281-
async changeUserAccessWithinAccount(
288+
export async function changeUserAccessWithinAccount(
282289
user_id: number,
283290
account_id: number,
284291
access: ACCOUNT_ACCESS
@@ -333,15 +340,14 @@ export default class AccountService {
333340
Note.. for each usage limit, you will need another pair of check/increment methods and of course the count and max limit in the account schema
334341
335342
How to use in a service method....
336-
async someServiceMethod(account_id: number, .....etc) {
337-
const accountService = new AccountService();
338-
const account = await accountService.checkAIGenCount(account_id);
343+
export async function someServiceMethod(account_id: number, .....etc) {
344+
const account = await AccountService.checkAIGenCount(account_id);
339345
... User is under the limit so do work
340-
await accountService.incrementAIGenCount(account);
346+
await AccountService.incrementAIGenCount(account);
341347
}
342348
*/
343349

344-
async getAccountWithPeriodRollover(account_id: number) {
350+
export async function getAccountWithPeriodRollover(account_id: number) {
345351
const account = await prisma_client.account.findFirstOrThrow({
346352
where: { id: account_id }
347353
});
@@ -366,8 +372,8 @@ export default class AccountService {
366372
return account;
367373
}
368374

369-
async checkAIGenCount(account_id: number) {
370-
const account = await this.getAccountWithPeriodRollover(account_id);
375+
export async function checkAIGenCount(account_id: number) {
376+
const account = await getAccountWithPeriodRollover(account_id);
371377

372378
if (account.ai_gen_count >= account.ai_gen_max_pm) {
373379
throw new AccountLimitError(
@@ -378,7 +384,7 @@ export default class AccountService {
378384
return account;
379385
}
380386

381-
async incrementAIGenCount(account: any) {
387+
export async function incrementAIGenCount(account: any) {
382388
return await prisma_client.account.update({
383389
where: { id: account.id },
384390
data: {

lib/services/auth.service.ts

+7-5
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ import generator from 'generate-password-ts';
66

77
const config = useRuntimeConfig();
88

9-
export default class AuthService {
10-
async getFullUserBySupabaseId(
9+
export namespace AuthService {
10+
export async function getFullUserBySupabaseId(
1111
supabase_uid: string
1212
): Promise<FullDBUser | null> {
1313
return prisma_client.user.findFirst({
@@ -16,14 +16,16 @@ export default class AuthService {
1616
});
1717
}
1818

19-
async getUserById(user_id: number): Promise<FullDBUser | null> {
19+
export async function getUserById(
20+
user_id: number
21+
): Promise<FullDBUser | null> {
2022
return prisma_client.user.findFirstOrThrow({
2123
where: { id: user_id },
2224
...fullDBUser
2325
});
2426
}
2527

26-
async createUser(
28+
export async function createUser(
2729
supabase_uid: string,
2830
display_name: string,
2931
email: string
@@ -65,7 +67,7 @@ export default class AuthService {
6567
});
6668
}
6769

68-
async deleteUser(user_id: number): Promise<FullDBUser> {
70+
export async function deleteUser(user_id: number): Promise<FullDBUser> {
6971
return prisma_client.user.delete({
7072
where: { id: user_id },
7173
...fullDBUser

lib/services/notes.service.ts

+14-12
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
11
import prisma_client from '~~/prisma/prisma.client';
22
import { openai } from './openai.client';
33
import { AccountLimitError } from './errors';
4-
import AccountService from './account.service';
4+
import { AccountService } from './account.service';
55

6-
export default class NotesService {
7-
async getAllNotes() {
6+
export namespace NotesService {
7+
export async function getAllNotes() {
88
return prisma_client.note.findMany();
99
}
1010

11-
async getNoteById(id: number) {
11+
export async function getNoteById(id: number) {
1212
return prisma_client.note.findUniqueOrThrow({ where: { id } });
1313
}
1414

15-
async getNotesForAccountId(account_id: number) {
15+
export async function getNotesForAccountId(account_id: number) {
1616
return prisma_client.note.findMany({ where: { account_id } });
1717
}
1818

19-
async createNote(account_id: number, note_text: string) {
19+
export async function createNote(account_id: number, note_text: string) {
2020
const account = await prisma_client.account.findFirstOrThrow({
2121
where: { id: account_id },
2222
include: { notes: true }
@@ -31,17 +31,19 @@ export default class NotesService {
3131
return prisma_client.note.create({ data: { account_id, note_text } });
3232
}
3333

34-
async updateNote(id: number, note_text: string) {
34+
export async function updateNote(id: number, note_text: string) {
3535
return prisma_client.note.update({ where: { id }, data: { note_text } });
3636
}
3737

38-
async deleteNote(id: number) {
38+
export async function deleteNote(id: number) {
3939
return prisma_client.note.delete({ where: { id } });
4040
}
4141

42-
async generateAINoteFromPrompt(userPrompt: string, account_id: number) {
43-
const accountService = new AccountService();
44-
const account = await accountService.checkAIGenCount(account_id);
42+
export async function generateAINoteFromPrompt(
43+
userPrompt: string,
44+
account_id: number
45+
) {
46+
const account = await AccountService.checkAIGenCount(account_id);
4547

4648
const prompt = `
4749
Write an interesting short note about ${userPrompt}.
@@ -56,7 +58,7 @@ export default class NotesService {
5658
n: 1
5759
});
5860

59-
await accountService.incrementAIGenCount(account);
61+
await AccountService.incrementAIGenCount(account);
6062

6163
return completion.data.choices[0].text;
6264
}

lib/services/util.service.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
export class UtilService {
2-
public static addMonths(date: Date, months: number): Date {
1+
export namespace UtilService {
2+
export function addMonths(date: Date, months: number): Date {
33
const d = date.getDate();
44
date.setMonth(date.getMonth() + +months);
55
if (date.getDate() != d) {
@@ -8,12 +8,12 @@ export class UtilService {
88
return date;
99
}
1010

11-
public static getErrorMessage(error: unknown) {
11+
export function getErrorMessage(error: unknown) {
1212
if (error instanceof Error) return error.message;
1313
return String(error);
1414
}
1515

16-
public static stringifySafely(obj: any) {
16+
export function stringifySafely(obj: any) {
1717
let cache: any[] = [];
1818
let str = JSON.stringify(obj, function (key, value) {
1919
if (typeof value === 'object' && value !== null) {

server/api/note.ts

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { H3Event, getQuery } from 'h3';
22
import { defineProtectedEventHandler } from '../defineProtectedEventHandler';
3-
import NotesService from '~/lib/services/notes.service';
3+
import { NotesService } from '~/lib/services/notes.service';
44

55
// Example API Route with query params ... /api/note?note_id=41
66
export default defineProtectedEventHandler(async (event: H3Event) => {
@@ -14,8 +14,7 @@ export default defineProtectedEventHandler(async (event: H3Event) => {
1414
}
1515
}
1616

17-
const notesService = new NotesService();
18-
const note = await notesService.getNoteById(+note_id);
17+
const note = await NotesService.getNoteById(+note_id);
1918

2019
return {
2120
note

server/middleware/authContext.ts

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { defineEventHandler, parseCookies, setCookie, getCookie } from 'h3';
22
import { serverSupabaseUser } from '#supabase/server';
3-
import AuthService from '~/lib/services/auth.service';
3+
import { AuthService } from '~/lib/services/auth.service';
44

55
import { User } from '@supabase/supabase-js';
66
import { FullDBUser } from '~~/lib/services/service.types';
@@ -27,11 +27,10 @@ export default defineEventHandler(async event => {
2727
if (user) {
2828
event.context.user = user;
2929

30-
const authService = new AuthService();
31-
let dbUser = await authService.getFullUserBySupabaseId(user.id);
30+
let dbUser = await AuthService.getFullUserBySupabaseId(user.id);
3231

3332
if (!dbUser && user) {
34-
dbUser = await authService.createUser(
33+
dbUser = await AuthService.createUser(
3534
user.id,
3635
user.user_metadata.full_name
3736
? user.user_metadata.full_name

server/routes/create-checkout-session.post.ts

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { ACCOUNT_ACCESS } from '~~/prisma/account-access-enum';
22
import Stripe from 'stripe';
3-
import AccountService from '~~/lib/services/account.service';
3+
import { AccountService } from '~~/lib/services/account.service';
44
import { AccountWithMembers } from '~~/lib/services/service.types';
55

66
const config = useRuntimeConfig();
@@ -14,8 +14,7 @@ export default defineEventHandler(async event => {
1414
`session.post.ts recieved price_id:${price_id}, account_id:${account_id}`
1515
);
1616

17-
const accountService = new AccountService();
18-
const account: AccountWithMembers = await accountService.getAccountById(
17+
const account: AccountWithMembers = await AccountService.getAccountById(
1918
account_id
2019
);
2120
let customer_id: string;
@@ -32,7 +31,7 @@ export default defineEventHandler(async event => {
3231
email: owner?.user.email
3332
});
3433
customer_id = customer.id;
35-
accountService.updateAccountStipeCustomerId(account_id, customer.id);
34+
AccountService.updateAccountStipeCustomerId(account_id, customer.id);
3635
} else {
3736
customer_id = account.stripe_customer_id;
3837
}

server/routes/webhook.post.ts

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import Stripe from 'stripe';
2-
import AccountService from '~~/lib/services/account.service';
2+
import { AccountService } from '~~/lib/services/account.service';
33

44
const config = useRuntimeConfig();
55
const stripe = new Stripe(config.stripeSecretKey, { apiVersion: '2022-11-15' });
@@ -56,8 +56,6 @@ export default defineEventHandler(async event => {
5656
});
5757
}
5858

59-
const accountService = new AccountService();
60-
6159
let current_period_ends: Date = new Date(
6260
subscription.current_period_end * 1000
6361
);
@@ -68,7 +66,7 @@ export default defineEventHandler(async event => {
6866
console.log(
6967
`updating stripe sub details subscription.current_period_end:${subscription.current_period_end}, subscription.id:${subscription.id}, stripe_product_id:${stripe_product_id}`
7068
);
71-
accountService.updateStripeSubscriptionDetailsForAccount(
69+
AccountService.updateStripeSubscriptionDetailsForAccount(
7270
subscription.customer.toString(),
7371
subscription.id,
7472
current_period_ends,

0 commit comments

Comments
 (0)