如何在Node.js中创建函数访问ArangoDB以适配Angular4前端?
Hey there! Glad you've got the basic connection up and running between Node.js and ArangoDB. Let's refactor your code into clean, reusable functions for individual data-fetching tasks—this will make it straightforward to hook up with your Angular4 frontend later.
Step 1: Clean Up Configuration & DB Connection
First, let's organize your config and ensure the database connection is initialized only once (no global scope mess, which keeps things maintainable).
Step 2: Build Reusable Task Functions
We'll wrap each data operation into its own async function. Using async/await makes asynchronous ArangoDB calls easy to read and debug—perfect for a beginner setup.
Step 3: Add Express Routes for Frontend Access
We'll map these functions to RESTful API endpoints so your Angular app can send HTTP requests to fetch data whenever it needs to.
Here's the refactored server.js with all these changes:
// BASE SETUP // ------------------------------ // Import required packages const arangojs = require('arangojs'); const aqlQuery = arangojs.aqlQuery; const express = require('express'); const bodyParser = require('body-parser'); // Initialize Express app const app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // ArangoDB Configuration & Connection // ------------------------------ const dbConfig = { host: '192.000.00.000', port: '8529', username: 'xyz', password: 'xyz', database: 'sgcdm_app' }; // Initialize database connection (only runs once!) const db = new arangojs.Database({ url: `http://${dbConfig.host}:${dbConfig.port}`, databaseName: dbConfig.database }); db.useBasicAuth(dbConfig.username, dbConfig.password); // Reusable Data-Fetching Functions // ------------------------------ // Get a single edge document by ID async function getEdgeById(edgeCollectionName, edgeId) { try { const collection = db.edgeCollection(edgeCollectionName); const edge = await collection.edge(edgeId); return edge; } catch (error) { console.error('Error fetching edge:', error); throw error; // Pass error to route to send proper response } } // Query all documents from a collection (adjust AQL for your needs) async function getCollectionData(collectionName) { try { const query = aqlQuery` FOR doc IN ${collectionName} RETURN doc `; const result = await db.query(query); return await result.all(); // Convert cursor to a usable array } catch (error) { console.error('Error querying collection:', error); throw error; } } // Get a single document from any collection by ID async function getDocumentById(collectionName, docId) { try { const collection = db.collection(collectionName); const document = await collection.document(docId); return document; } catch (error) { console.error('Error fetching document:', error); throw error; } } // Express Routes (Frontend Access Points) // ------------------------------ const port = process.env.PORT || 8080; // Fetch a specific edge from 'included_in' collection app.get('/api/edges/included_in/:id', async (req, res) => { try { const edge = await getEdgeById('included_in', req.params.id); res.json(edge); } catch (error) { res.status(500).json({ message: 'Failed to fetch edge', error: error.message }); } }); // Fetch all data from any collection app.get('/api/collection/:name', async (req, res) => { try { const data = await getCollectionData(req.params.name); res.json(data); } catch (error) { res.status(500).json({ message: 'Failed to fetch collection data', error: error.message }); } }); // Fetch a single document by ID from any collection app.get('/api/document/:collection/:id', async (req, res) => { try { const document = await getDocumentById(req.params.collection, req.params.id); res.json(document); } catch (error) { res.status(500).json({ message: 'Failed to fetch document', error: error.message }); } }); // Start the server app.listen(port, () => { console.log(`Magic happens on port ${port}`); });
Key Notes for Your Setup:
- Error Handling: Each function catches database errors and passes them to the Express route, which sends a clear error response to your Angular app—no silent failures!
- Reusability: You can add more functions (like creating/updating documents) using the same
async/try/catchpattern. - RESTful Routes: The endpoints are structured so your Angular app can easily call them with
HttpClient.
Testing the Endpoints
Use tools like Postman or curl to test these routes before connecting to Angular:
- Get a specific edge:
GET http://localhost:8080/api/edges/included_in/595783 - Get all data from a collection:
GET http://localhost:8080/api/collection/included_in - Get a single document:
GET http://localhost:8080/api/document/your_collection_name/your_doc_id
Quick Angular4 Integration Tip
In your Angular component/service, use HttpClient to call these endpoints:
import { HttpClient } from '@angular/common/http'; // In your component/service constructor constructor(private http: HttpClient) {} // Example function to fetch an edge getEdgeById(edgeId: string) { return this.http.get(`http://your-node-server-url/api/edges/included_in/${edgeId}`); }
内容的提问来源于stack exchange,提问作者cantona_7

