1+ import 'dotenv/config' ;
2+ import { Hono } from "hono" ;
3+ import { db } from '../db.js' ;
4+ import { zValidator } from '@hono/zod-validator' ;
5+ import { SubscriptionCreate } from '../schema/index.js' ;
6+ import { eq } from 'drizzle-orm' ;
7+ import { subscriptionsTable } from '../db/schema/subscriptions.js' ;
8+ import { plansTable } from '../db/schema/plans.js' ;
9+ import { customersTable } from '../db/schema/customers.js' ;
10+
11+ const subscriptionsRouter = new Hono ( )
12+
13+ subscriptionsRouter . get ( "/" , async ( c ) => {
14+ const subscriptions = await db . select ( ) . from ( subscriptionsTable )
15+
16+ return c . json ( {
17+ status : true ,
18+ data : subscriptions ,
19+ } , 200 )
20+ } )
21+
22+ subscriptionsRouter . post ( "/" ,
23+ zValidator ( 'json' , SubscriptionCreate ) ,
24+ async ( c ) => {
25+ const validateReq = c . req . valid ( 'json' )
26+ const api = await fetch ( `${ process . env . PAYSTACK_BASE_URL } /subscription` , {
27+ method : "POST" ,
28+ headers : {
29+ "Authorization" : `Bearer ${ process . env . PAYSTACK_SECRET_KEY } ` ,
30+ 'Content-Type' : "application/json"
31+ } ,
32+ body : JSON . stringify ( validateReq )
33+ } )
34+
35+ const data = await api . json ( )
36+
37+ if ( ! data [ "status" ] ) {
38+ return c . json ( {
39+ status : false ,
40+ data : { }
41+ } , 500 )
42+ }
43+
44+ const {
45+ subscription_code,
46+ status,
47+ plan : planCode ,
48+ customer : customerCode ,
49+ email_token,
50+ next_payment_date
51+ } = data [ "data" ]
52+ const plan = await db . select ( { id : plansTable . id } )
53+ . from ( plansTable )
54+ . where ( eq ( plansTable . code , planCode ) )
55+ const customer = await db . select ( { id : customersTable . id } )
56+ . from ( customersTable )
57+ . where ( eq ( customerCode . code , customerCode ) )
58+
59+ const subscription = await db . insert ( subscriptionsTable )
60+ . values ( {
61+ code : subscription_code ,
62+ status : status ,
63+ emailToken : email_token ,
64+ plan : plan [ 0 ] . id ,
65+ customer : customer [ 0 ] . id ,
66+ nextPaymentDate : next_payment_date
67+ } )
68+ . returning ( )
69+
70+ return c . json ( {
71+ status : true ,
72+ data : subscription [ 0 ]
73+ } , 201 )
74+ }
75+ )
76+
77+
78+ export default subscriptionsRouter
0 commit comments