Skip to content

InfluxDB and MongoDB from GraphQL

Learn how to combine MongoDB and InfluxDB data sources using GraphQL with Apollo Server and TypeScript for unified queries.

Here's an example of how you can use GraphQL to combine calls to MongoDB and InfluxDB data sources using TypeScript:

import { ApolloServer, gql } from 'apollo-server';
import { MongoClient } from 'mongodb';
import { createInfluxGraphQLSchema } from 'influx-graphql';
import Influx from 'influx';
 
// Create a new MongoDB client instance
const mongoClient = new MongoClient('mongodb://localhost:27017', { useNewUrlParser: true });
 
// Create a new InfluxDB client instance
const influx = new Influx.InfluxDB({
  host: 'localhost',
  database: 'mydb',
});
 
// Connect to the MongoDB client and start the InfluxDB client
Promise.all([
  mongoClient.connect(),
  influx.ping(),
]).then(() => {
  console.log('Connected to MongoDB and InfluxDB');
}).catch((error: Error) => {
  console.error('Error connecting to MongoDB and InfluxDB:', error);
});
 
// Define a GraphQL schema for MongoDB using Apollo Server
const mongoSchema = gql`
  type User {
    id: ID!
    name: String!
    email: String!
  }
 
  type Query {
    user(id: ID!): User
  }
`;
 
// Define resolvers for the MongoDB schema
const mongoResolvers = {
  Query: {
    user: async (parent: any, args: { id: string }, context: { db: any }) => {
      const user = await context.db.collection('users').findOne({ _id: args.id });
      return {
        id: user._id,
        name: user.name,
        email: user.email,
      };
    },
  },
};
 
// Create a GraphQL schema for InfluxDB using influx-graphql
const influxSchema = createInfluxGraphQLSchema({
  // Specify the InfluxDB client instance
  influx,
  // Specify the database to use
  database: 'mydb',
});
 
// Define a GraphQL schema that combines the MongoDB and InfluxDB schemas
const schema = gql`
  type User {
    id: ID!
    name: String!
    email: String!
    lastLogin: Float!
  }
 
  type Query {
    user(id: ID!): User
  }
`;
 
// Define resolvers for the combined schema
const resolvers = {
  Query: {
    user: async (parent: any, args: { id: string }, context: { db: any }) => {
      const user = await context.db.collection('users').findOne({ _id: args.id });
      const lastLogin = await influx.query(`
        SELECT last("login") AS "lastLogin"
        FROM "logins"
        WHERE "userId" = '${args.id}'
        GROUP BY time(1d)
        ORDER BY time DESC
        LIMIT 1
      `);
      return {
        id: user._id,
        name: user.name,
        email: user.email,
        lastLogin: lastLogin[0]?.lastLogin ?? 0,
      };
    },
  },
};
 
// Create an Apollo Server instance with the combined schema and resolvers
const server = new ApolloServer({
  typeDefs: schema,
  resolvers,
  context: () => ({
    db: mongoClient.db('mydb'),
  }),
});
 
// Start the Apollo Server
server.listen().then(({ url }) => {
  console.log(`Server running at ${url}`);

In this example, we use TypeScript and the "apollo-server", "mongodb", "influx-graphql", and "influx" packages to create a GraphQL server that combines calls to MongoDB and InfluxDB data sources.

Tags

mongodbinfluxdbgraphqlnpmApollo ServerTypeScriptData Integration