Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'apollo-server-express' 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.
import resolvers from './resources/resolvers';
//Set Port. If environment variable exist use it instead
const GRAPHQL_PORT = process.env.GRAPHQL_PORT || 3000;
// Initialize the HTTP server using express
const server = express();
//Generate the executable schema. Note that makeExecutableSchema expects typeDefs and resolvers as input
const schema = makeExecutableSchema({
typeDefs,
resolvers
});
//Define the GraphQL endpoint using the Apollo GraphQL Server. Note that graphqlExress expects the schema constant
server.use('/graphql', bodyParser.json(), graphqlExpress({
schema
}));
//Implement the Graphiql client available that comes with the Apollo GraphQL Server
server.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql'
}));
// Start the server
server.listen(GRAPHQL_PORT, () => {
console.log('Go to http://localhost:' + GRAPHQL_PORT + '/graphiql to run queries!');
});
schema: hasuraGraphSchema,
link: hasuraLink,
});
const finalSchema = mergeSchemas({
schemas: [
executableWeatherSchema,
executableHasuraSchema,
linkHasuraTypeDefs
],
resolvers: hasuraWeatherResolvers
});
const app = new Express();
app.use('/graphql', bodyParser.json(), graphqlExpress({ schema: finalSchema}));
app.use('/graphiql',graphiqlExpress({endpointURL: '/graphql'}));
app.listen(8080);
console.log('Server running. Open http://localhost:8080/graphiql to run queries.');
} // end of async run
$map: {
input: '$permissions.code',
as: 'code',
in: '$$code'
}
},
_id: 0
}
}
])
.toArray()
console.log(userRoles[0].permissions)
if (userRoles[0].permissions.indexOf(permission) === -1) {
throw new ForbiddenError('You are not authorized for this resource.')
}
// console.log('userRole', userRole)
return resolve.apply(this, args)
}
}
throw new AuthenticationError(
'Authentication token is invalid, please try again.'
)
}
// console.log(currentUser._id, permission)
const role = await getMongoRepository(Role).find({
where: {
userId: currentUser._id,
'permissions.code': permission
}
})
if (!role) {
throw new ForbiddenError('You are not authorized for this resource.')
}
// console.log('Role', role)
return resolve.apply(this, args)
}
}
throw new AuthenticationError(
'Authentication token is invalid, please try again.'
)
}
// console.log(currentUser._id, path)
const role = await getMongoRepository(Role).find({
where: {
userId: currentUser._id,
path: { $regex: `.*${path}|${path.toLowerCase()}.*` },
},
})
if (!role) {
throw new ForbiddenError('You are not authorized for this resource.')
}
// console.log('Role', role)
return resolve.apply(this, args)
}
}
if (process.env.NODE_ENV !== 'development') {
// In production, make sure a valid token is present before doing anything.
app.use(requireValidJWT);
// If there’s an error, send it as JSON so it’s useful in the GraphQL output.
app.use((err, _, res, next) => {
if (err) {
res.json(err);
}
next();
});
}
// Set up the GraphQL server.
const server = new ApolloServer({
typeDefs,
resolvers,
playground: process.env.NODE_ENV === 'development'
});
server.applyMiddleware({ app, cors: true });
// Turn the Express server into a lambda-compatible handler function.
const handler = serverless(app);
export const graphql = async (event, context) => {
// Prevents Lambda cold starts
if (event.source === 'serverless-plugin-warmup') {
return 'Lambda is warm!';
}
const setupGraphQLServer = () => {
// setup server
const graphQLServer = express()
// /api/graphql
graphQLServer.use(
"/graphql",
bodyParser.json(),
graphqlExpress({ schema, context: {} })
)
// /api/graphiql
graphQLServer.use(
"/graphiql",
graphiqlExpress({ endpointURL: "graphql" })
)
// /api/schema
graphQLServer.use("/schema", (req, res) => {
res.set("Content-Type", "text/plain")
res.send(printSchema(schema))
})
return graphQLServer
}
app.get('/login-callback', ...loginCallbacks.loginCallback)
app.post('/login-callback', ...loginCallbacks.loginCallback)
}
const executableSchema = makeExecutableSchema({
typeDefs: schema,
resolvers,
allowUndefinedInResolve: false
})
addMockFunctionsToSchema({
schema: executableSchema,
mocks,
preserveResolvers: true
})
app.use('/graphql', graphqlExpress((request) => ({
schema: executableSchema,
context: {
loaders: createLoaders(),
user: request.user,
awsContext: request.awsContext || null,
awsEvent: request.awsEvent || null,
remainingMilliseconds: () => (
(request.awsContext && request.awsContext.getRemainingTimeInMillis)
? request.awsContext.getRemainingTimeInMillis()
: 5 * 60 * 1000 // default saying 5 min, no matter what
)
}
})))
app.get('/graphiql', graphiqlExpress({
endpointURL: '/graphql'
}))
// something went bad when configuring the graphql server, we do not
// swallow the error and display it in the server-side logs
Logger.error(error, "[GraphQL Server] Something bad happened when handling a request on the GraphQL server");
// return the default graphql options anyway
return defaultGraphQLOptions;
}
})
);
// Start GraphiQL if enabled
if (config.graphiql) {
// GraphiQL endpoint
expressServer.use(
config.graphiqlPath,
graphiqlExpress({
// GraphiQL options
...config.graphiqlOptions,
// endpoint of the graphql server where to send requests
endpointURL: config.path
})
);
}
// bind the specified paths to the Express server running Apollo + GraphiQL
WebApp.connectHandlers.use(expressServer);
}
async execute(command: RegisterUserCommand): Promise {
Logger.log('Async RegisterUserHandler...', 'RegisterUserCommand');
const { cmd } = command;
try {
const userExist: boolean = await this.userRepository.exist({
'emails.address': cmd.email,
});
if (userExist) {
throw new AuthenticationError('User with this authentication method already exist');
}
// @ts-ignore
const user: UserEntity = {
firstname: cmd.firstname,
lastname: cmd.lastname,
emails: [{
address: cmd.email,
primary: true,
verified: false,
verificationCode: generateVerificationCode(6, { type: 'number' }),
}],
roles: ['member'],
services: {
password: {
hashed: cmd.password,