Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'apollo-server' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
(async () => {
try {
const info = await connectDatabase();
console.log(`Connected to mongodb 🍃 at ${info.host}:${info.port}/${info.name}`);
} catch (error) {
console.error('Unable to connect to database');
process.exit(1);
}
const server = new ApolloServer({
resolvers: globalResolvers,
typeDefs: globalQuery,
// user authentication
context: async ({ req }) => {
const token = req.headers.authorization ? req.headers.authorization : '';
const { user } = await getUser(token);
return {
user,
};
},
tracing: true,
});
const graphqlPort = 3000;
server.setGraphQLPath('graphql');
server.listen(graphqlPort).then(({ url }) => {
console.log(`🚀 Apollo server ready on ${url}`);
// Increment likes on tweet, in real life you'd use a transaction!
let tweetDoc = await tweetRef.get();
const tweet = tweetDoc.data() as Tweet;
await tweetRef.update({ likes: tweet.likes + 1 });
tweetDoc = await tweetRef.get();
return tweetDoc.data();
} catch (error) {
throw new ApolloError(error);
}
}
}
};
const server = new ApolloServer({
typeDefs,
resolvers,
introspection: true
});
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
async function bootstrap() {
// Build the TypeGraphQL schema
const schema = await buildSchema({
resolvers: [SampleResolver],
});
// Create GraphQL server
const server = new ApolloServer({
schema,
playground: true,
// you can pass the endpoint path for subscriptions
// otherwise it will be the same as main graphql endpoint
// subscriptions: "/subscriptions",
});
// Start the server
const { url } = await server.listen(4000);
console.log(`Server is running, GraphQL Playground available at ${url}`);
}
// create Redis-based pub-sub
const pubSub = new RedisPubSub({
publisher: new Redis(options),
subscriber: new Redis(options),
});
// Build the TypeGraphQL schema
const schema = await buildSchema({
resolvers: [RecipeResolver],
validate: false,
pubSub, // provide redis-based instance of PubSub
});
// Create GraphQL server
const server = new ApolloServer({ schema });
// Start the server
const { url } = await server.listen(4000);
console.log(`Server is running, GraphQL Playground available at ${url}`);
}
const chat = await group.getChat();
return Boolean(chat.id === payload.messageAdded.chatId);
},
),
},
groupAdded: {
subscribe: withFilter(
() => pubsub.asyncIterator(GROUP_ADDED_TOPIC),
(payload, args) => {
// console.log(JSON.stringify(payload, null, 2));
return Boolean(true /*args.userId === payload.groupAdded.userId*/);
},
),
},
messageInGroupAdded: {
subscribe: withFilter(
() => pubsub.asyncIterator(MESSAGE_IN_GROUP_ADDED_TOPIC),
(payload, args) => {
console.log(JSON.stringify(payload, null, 2));
return Boolean(
true /*args.userId === payload.defaultGroupAdded.userId*/,
);
},
),
},
},
Mutation: {
async addFriend(_, { userId, friendId }, ctx) {
const user = await UserModel.findOne({
where: { id: userId },
});
module.exports = function(app, db) {
// Register graphql server
app.use("/graphql", auth.isAuthenticatedOrApiKey, ApolloServer( (req) => {
const query = req.query.query || req.body.query;
if (query && query.length > 2000) {
// None of our app's queries are this long
// Probably indicates someone trying to send an overly expensive query
throw new Error("Query too large.");
}
return {
graphiql: config.isDevMode(),
pretty: config.isDevMode(),
printErrors: config.isDevMode(),
schema: Schema,
resolvers: Resolvers,
logger: { log: (e) => console.error(e.stack) },
context: {
user: req.user,
import express from 'express';
import bodyParser from 'body-parser';
import { apolloExpress, graphiqlExpress } from 'apollo-server';
import schema from '/domain/schemas';
import connectors from './connectors';
import resolvers from './resolvers';
// Initial fixtures
require('./fixtures').run(connectors.MongoDB.connect());
const PORT = 8080;
const app = express();
app.use('/graphql', bodyParser.json(), apolloExpress({
schema,
resolvers,
context: {},
formatError(error) {
console.error(error.stack);
return error;
},
}));
app.use(
'/graphiql',
graphiqlExpress({
endpointURL: '/graphql',
})
);
void (async function bootstrap() {
// build TypeGraphQL executable schema
const schema = await buildSchema({
resolvers: [ExampleResolver],
authChecker, // register auth checking function
});
// Create GraphQL server
const server = new ApolloServer({
schema,
context: () => {
const ctx: Context = {
// create mocked user in context
// in real app you would be mapping user from `req.user` or sth
user: {
id: 1,
name: "Sample user",
roles: ["REGULAR"],
},
};
return ctx;
},
});
// Start the server
function makeServer() {
// enable hot-reload server side
// eslint-disable-next-line global-require
const graphqlSchema = require('./graphql').default;
return new ApolloServer({
typeDefs: graphqlSchema.typeDefs,
/* Apollo is mutating resolvers */
resolvers: { ...graphqlSchema.resolvers },
playground: playgroundConfig,
formatError: (error) => {
log.error(error);
return error;
},
formatResponse: (response) => {
log.info(response);
return response;
},
});
}
import { ApolloServer, PubSub } from 'apollo-server';
import * as mongoose from 'mongoose';
import * as dotenv from 'dotenv';
import graphqlTypes from './graphqlTypes';
import resolvers from './resolvers';
import { getUser } from './auth/authMethods';
import { MongoError } from 'mongodb';
dotenv.config();
const pubsub = new PubSub();
const server = new ApolloServer({
resolvers,
typeDefs: graphqlTypes,
// @ts-ignore
context: async ({ req, connection }) => {
if (connection) {
return {
...connection.context,
pubsub,
};
} else {
// check from req
const token = req.headers.authorization ? req.headers.authorization : '';
const user = await getUser(token);
return {