gitdb-database
Version:
A production-ready CLI tool for managing a NoSQL database using GitHub repositories as storage
101 lines • 3.53 kB
JavaScript
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import { registerApiRoutes } from './api/index.js';
import { spawn } from 'child_process';
import fetch from 'node-fetch';
import { ApolloServer } from 'apollo-server-express';
import { buildGraphQLSchemaAndResolvers } from './graphql.js';
const app = express();
const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 7896;
app.use(cors());
app.use(bodyParser.json());
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`[${new Date().toISOString()}] ${req.method} ${req.originalUrl} ${res.statusCode} - ${duration}ms`);
});
next();
});
app.get('/health', (req, res) => {
res.send('GraphQL Server is healthy');
});
async function ensureOllamaRunning() {
const ollamaUrl = 'http://localhost:11434';
try {
// Check if Ollama is running
const res = await fetch(ollamaUrl);
if (res.ok) {
console.log('🤖 Ollama is already running.');
return;
}
}
catch {
// Not running, try to start
try {
const child = spawn('ollama', ['run', 'phi3'], {
detached: true,
stdio: 'ignore',
});
child.unref();
console.log('🤖 Ollama (phi3) started in background.');
}
catch (err) {
console.warn('⚠️ Could not start Ollama. AI features may not work.');
}
}
}
let apolloServer = null;
async function createApolloServer() {
const { typeDefs, resolvers } = await buildGraphQLSchemaAndResolvers();
return new ApolloServer({
typeDefs,
resolvers,
formatError: (err) => {
const isDev = process.env.NODE_ENV !== 'production';
return {
message: err.message,
code: err.extensions?.code || 'INTERNAL_SERVER_ERROR',
path: err.path,
locations: err.locations,
...(isDev && { stack: err.extensions?.exception?.stacktrace || err.stack })
};
}
});
}
registerApiRoutes(app);
app.get('/', (req, res) => {
res.send('GitDB Server is running. See /api/v1 for API.');
});
app.post('/graphql/reload-schema', async (req, res) => {
// Only allow local requests
const remote = req.ip || req.connection.remoteAddress || '';
if (!['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(remote)) {
return res.status(403).json({ error: 'Forbidden' });
}
try {
if (apolloServer) {
await apolloServer.stop();
}
apolloServer = await createApolloServer();
await apolloServer.start();
apolloServer.applyMiddleware({ app: app, path: '/graphql' });
return res.json({ success: true, message: 'GraphQL schema reloaded' });
}
catch (err) {
return res.status(500).json({ error: err.message || 'Failed to reload schema' });
}
});
(async () => {
await ensureOllamaRunning();
apolloServer = await createApolloServer();
await apolloServer.start();
apolloServer.applyMiddleware({ app: app, path: '/graphql' });
app.listen(PORT, () => {
console.log(`🚀 GitDB Server running at http://localhost:${PORT}`);
console.log('API root: /api/v1');
console.log(`GraphQL endpoint: http://localhost:${PORT}/graphql`);
});
})();
//# sourceMappingURL=server.js.map