-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·201 lines (168 loc) · 6.14 KB
/
cli.js
File metadata and controls
executable file
·201 lines (168 loc) · 6.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#!/usr/bin/env node
import { spawn } from 'node:child_process';
import path from 'node:path';
import fs from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Routes directory for Express routes
const routesDir = path.join(process.cwd(), 'routes', 'pi_payment');
const routesIndexFile = path.join(routesDir, 'index.ts');
// Ensure routes directory exists
const ensureRoutesDir = async () => {
await fs.mkdir(routesDir, { recursive: true });
};
// Route templates for each endpoint
const routeTemplates = {
approve: `import { Request, Response } from 'express';
import { approveHandler } from 'pi-sdk-express';
export async function approve(req: Request, res: Response) {
// TODO: Add your custom logic here (e.g., user lookup, transaction creation)
// Example:
// const { accessToken, paymentId } = req.body;
// const user = await findOrCreateUser(accessToken);
// const transaction = await createTransaction(paymentId, user.id);
return approveHandler(req, res);
}`,
complete: `import { Request, Response } from 'express';
import { completeHandler } from 'pi-sdk-express';
export async function complete(req: Request, res: Response) {
// TODO: Add your custom logic here (e.g., update transaction status)
// Example:
// const { paymentId, transactionId } = req.body;
// await updateTransaction(paymentId, { state: 'completed', transactionId });
return completeHandler(req, res);
}`,
cancel: `import { Request, Response } from 'express';
import { cancelHandler } from 'pi-sdk-express';
export async function cancel(req: Request, res: Response) {
// TODO: Add your custom logic here (e.g., update transaction status)
// Example:
// const { paymentId } = req.body;
// await updateTransaction(paymentId, { state: 'cancelled' });
return cancelHandler(req, res);
}`,
error: `import { Request, Response } from 'express';
import { errorHandler } from 'pi-sdk-express';
export async function error(req: Request, res: Response) {
// TODO: Add your custom logic here (e.g., log error to database)
// Example:
// const { paymentId, error } = req.body;
// await logError(paymentId, error);
return errorHandler(req, res);
}`,
incomplete: `import { Request, Response } from 'express';
import { incompleteHandler, IncompletePaymentDecision } from 'pi-sdk-express';
export async function incomplete(req: Request, res: Response) {
// TODO: Add your custom logic here to decide whether to complete or cancel
// Example:
// const { paymentId, transactionId } = req.body;
// const decision = await reviewIncompletePayment(paymentId, transactionId);
// return incompleteHandler(req, res, async (pid, tid) => decision);
return incompleteHandler(req, res);
}`
};
// Generate routes index file
const generateRoutesIndex = async () => {
const content = `// Pi Payment Routes
// Generated by pi-sdk-express CLI
import { Router } from 'express';
import { approve } from './approve';
import { complete } from './complete';
import { cancel } from './cancel';
import { error } from './error';
import { incomplete } from './incomplete';
const router = Router();
router.post('/approve', approve);
router.post('/complete', complete);
router.post('/cancel', cancel);
router.post('/error', error);
router.post('/incomplete', incomplete);
export default router;
`;
await fs.writeFile(routesIndexFile, content, 'utf8');
};
// Generate individual route files
const generateRouteFiles = async () => {
const endpoints = ['approve', 'complete', 'cancel', 'error', 'incomplete'];
for (const endpoint of endpoints) {
const routeFile = path.join(routesDir, `${endpoint}.ts`);
if (!(await fileExists(routeFile))) {
await fs.writeFile(routeFile, routeTemplates[endpoint], 'utf8');
console.log(`✓ Created ${routeFile}`);
} else {
console.log(`⊘ Skipped ${routeFile} (already exists)`);
}
}
};
// Generate example Express app file
const generateAppExample = async () => {
const appExampleFile = path.join(process.cwd(), 'app.server.ts');
if (!(await fileExists(appExampleFile))) {
const content = `import express from 'express';
import { createPiPaymentRouter } from 'pi-sdk-express';
import piPaymentRoutes from './routes/pi_payment';
const app = express();
// Required: JSON body parser middleware
app.use(express.json());
// Serve static files
app.use(express.static(join(__dirname, 'public')));
// Serve js SDK (for frontend)
app.use(
'/sdk',
express.static(
join(__dirname, 'node_modules/pi-sdk-js/dist'),
{
setHeaders(res, path) {
if (path.endsWith('.js')) {
res.setHeader('Content-Type', 'application/javascript');
}
}
}
)
);
// Mount Pi payment routes
app.use('/pi_payment', createPiPaymentRouter());
// Option 1: Use the generated routes
app.use('/pi_payment', piPaymentRoutes);
// Option 2: Use the router factory directly
// app.use('/pi_payment', createPiPaymentRouter({
// incompleteCallback: async (paymentId, transactionId) => {
// // Your custom logic
// return 'complete';
// }
// }));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(\`Server running on http://localhost:\${PORT}\`);
});
`;
await fs.writeFile(appExampleFile, content, 'utf8');
console.log(`✓ Created ${appExampleFile}`);
}
};
async function fileExists(file) {
try {
await fs.access(file);
return true;
} catch {
return false;
}
}
// Main execution
ensureRoutesDir()
.then(() => generateRouteFiles())
.then(() => generateRoutesIndex())
.then(() => generateAppExample())
.then(() => {
console.log('\n✅ Pi SDK Node.js routes generated successfully!');
console.log('\nNext steps:');
console.log('1. Review the generated files in routes/pi_payment/');
console.log('2. Add your custom business logic to each route handler');
console.log('3. Mount the routes in your Express app (see app.example.ts)');
console.log('4. Set PI_API_KEY environment variable');
})
.catch((err) => {
console.error('Error generating routes:', err);
process.exit(1);
});