Skip to content

Commit

Permalink
fix:api
Browse files Browse the repository at this point in the history
  • Loading branch information
pandaind committed Oct 14, 2024
1 parent 900fada commit ee78096
Show file tree
Hide file tree
Showing 5 changed files with 220 additions and 110 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.vercel
118 changes: 48 additions & 70 deletions api/index.js
Original file line number Diff line number Diff line change
@@ -1,84 +1,62 @@
const { createClientFromSpec } = require('@stoplight/prism-http/dist/client');
const { createInstance} = require('@stoplight/prism-http');
const { parse } = require('url');
// index.js
const { createInstance } = require('@stoplight/prism-http');
const { createLogger } = require('@stoplight/prism-core');
const fs = require('fs');
const path = require('path');
const fs = require('fs').promises;
const yaml = require('js-yaml'); // For parsing YAML OpenAPI files

async function initPrism() {
try {
const specPath = path.join(__dirname, '../pos.yml');
const specContent = fs.readFileSync(specPath, 'utf8');
const spec = yaml.load(specContent); // YAML parser

// Create Prism instance
const prism = createInstance(
{ config: { mock: { dynamic: true } }, components: { logger: createLogger() } },
spec
);

let prism;


const initializePrism = async () => {
const specPath = path.join(__dirname, '../pos.yml');
const specContent = await fs.readFile(specPath, 'utf8');
const client = await createClientFromSpec(specContent, { format: 'yaml' });
prism = createInstance({ config: { mock: { dynamic: true } } }, client);
};

module.exports = async (req, res) => {
if (!prism) {
try {
await initializePrism();
} catch (error) {
console.error('Error initializing Prism:', error);
res.statusCode = 500;
res.end('Internal Server Error during initialization');
return;
}
}

// Parse the URL and remove the '/api' prefix
const parsedUrl = parse(req.url, true);
const requestPath = parsedUrl.pathname.replace(/^\/api/, '') || '/';

// Set up the Prism request object
const request = {
method: req.method,
url: {
path: requestPath,
query: parsedUrl.query,
},
headers: req.headers,
};

// Collect the request body if present
let body = '';
for await (const chunk of req) {
body += chunk;
}
if (body) {
request.body = body;
return prism;
} catch (error) {
console.error('Error loading OpenAPI spec:', error);
throw new Error('Failed to initialize Prism: ' + error.message);
}
}

// CORS headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');

// Handle preflight requests
if (req.method === 'OPTIONS') {
res.statusCode = 204;
res.end();
return;
}

async function handleRequest(req, res) {
try {
const prism = await initPrism();

// Create the request object for Prism
const request = {
method: req.method,
url: {
path: req.url,
query: req.query,
},
headers: req.headers,
body: req.body,
};

console.log('Sending request to Prism:', request);

// Get the mocked response from Prism
const response = await prism.request(request);

res.statusCode = response.statusCode;
for (const [key, value] of Object.entries(response.headers || {})) {
res.setHeader(key, value);
if (!response) {
throw new Error('Prism response is undefined');
}

if (response.body) {
res.end(typeof response.body === 'string' ? response.body : JSON.stringify(response.body));
} else {
res.end();
}
// Return the response to the client
res.status(response.output.statusCode).set(response.output.headers || {}).send(response.output.body);
} catch (error) {
console.error('Error processing request:', error);
res.statusCode = 500;
res.end('Internal Server Error during request processing');
console.error('Error:', error);
res.status(500).send({ error: 'An error occurred', details: error.message });
}
};
}


// Export the handler for use with serverless functions or local development
module.exports = handleRequest;
Loading

0 comments on commit ee78096

Please sign in to comment.