Skip to content
Snippets Groups Projects
Commit 48a3c0a3 authored by Wilson JALLET's avatar Wilson JALLET :money_with_wings:
Browse files

Remplacement de express-graphql par Apollo Server

parent 70a0a9d8
No related branches found
No related tags found
No related merge requests found
......@@ -65,9 +65,15 @@ Il est accessible au path `/adminview/admin` ; n'importe quel path devrait redir
Le panneau d'administration sert (ou plutôt, servira à terme) à accéder directement à la BDD propre de sigma. On accède à la table `table_name` par une requête GET à `/adminview/db/table_name`' et aux colonnes `columns` de cette table par une requête GET à `/adminview/db/table_name`?columns=`columns`.
Ces pages sont protégées pour n'être accessibles qu'en étant authentifié.
### GraphiQL et Voyager
### GraphQL Playground et Voyager
A partir du panneau d'admin, en faisant des requêtes GET à `/graphiql` et `/voyager` respectivement, on accède à GraphiQL et à GraphQL Voyager. Ces pages sont protégées pour n'être accessibles qu'en étant authentifié.
Accéder via un navigateur à `/graphql` et `/voyager` respectivement renvoie les apps GraphQL Playground et GraphQL Voyager.
Il s'agit du même `/graphql` que l'_endpoint_ de l'API, mais le serveur est configuré de sorte à renvoyer Playground lorsqu'il détecte un accès via navigateur. Les requêtes dans le Playground sont donc soumises au mêmes permissions que dans l'API.
L'app Voyager permet de visualiser le « graphe » sous-jacent à la structure de l'API. Cet _endpoint_ devrait être protégé **en prod**.
**En production**,
## Scripts
......
This diff is collapsed.
......@@ -17,6 +17,7 @@
"author": "Binet Réseau",
"license": "ISC",
"dependencies": {
"apollo-server-express": "^2.0.4",
"body-parser": "^1.18.3",
"colors": "^1.3.2",
"connect-ensure-login": "^0.1.1",
......@@ -25,7 +26,6 @@
"copy-webpack-plugin": "^4.5.2",
"cors": "^2.8.4",
"express": "^4.16.2",
"express-graphql": "^0.6.12",
"express-jwt": "^5.3.1",
"express-session": "^1.15.6",
"file-loader": "^1.1.11",
......
......@@ -3,18 +3,17 @@
* @author akka vodol
*/
import { makeExecutableSchema } from 'graphql-tools';
import actionDefs from './typeDefs/actions.graphql';
import objectDefs from './typeDefs/objects.graphql';
import { resolvers } from './resolvers';
const typeDefs = actionDefs.concat(objectDefs);
const schema = makeExecutableSchema({
const schema = {
typeDefs,
resolvers,
logger: {log: e => console.log(e)},
inheritResolversFromInterfaces: true
});
};
export default schema;
\ No newline at end of file
......@@ -8,5 +8,5 @@ import colors from 'colors';
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(colors.blue("Express server listening on port %s."), port);
console.log(colors.blue("🚀 Server ready on port %s."), port);
});
File moved
......@@ -13,12 +13,14 @@ import express from 'express';
import bodyParser from 'body-parser';
// packages pour graphql
import { express as graphqlVoyager } from 'graphql-voyager/middleware';
import graphqlHTTP from 'express-graphql'; // new name of 'graphql-server-express' (mai 2018). cf npmjs.com.
// replacement of express-graphql, which hasn't been updated in 6 months
import { ApolloServer } from 'apollo-server-express';
// typeDefs and resolvers
import schema from './graphql/schema';
// packages pour adminview
import { ensureLoggedIn } from 'connect-ensure-login';
import flash from 'connect-flash';
import router from './admin_view/admin.router';
import router from './routing/admin.router';
// packages pour l'authentification
import passport from 'passport';
import session from 'express-session';
......@@ -189,44 +191,54 @@ app.post('/login',
*/
const environment = process.env.NODE_ENV || 'development';
app.use('/graphql',
graphqlHTTP(async (req, res, params) => {
// vary the options *on a per-request basis*
let uid;
let password;
/**
* @desc Define GraphQL request context object, through a callback, with authorization.
* See: https://github.com/apollographql/apollo-server/blob/master/docs/source/best-practices/authentication.md
*
*/
const context = async ({ req }) => {
let uid;
let password;
console.log("Responding to graphql request...");
console.log(`
| User: ${req.user ? req.user.uid : "none"}
| Authorization: ${req.headers.authorization}
| Authenticated: ${req.isAuthenticated()}
`.trim());
if(req.isAuthenticated()) {
console.log("graphql API is receiving a request from an authenticated user! \\o/");
try {
uid = req.user.uid;
password = "mythe";
} catch (err) {
console.log("Error: req is authenticated, but pb when trying to extract uid from req.user. Probably user was either not serialized or not deserialized properly");
console.log(err);
}
} else {
// FOR DEVELOPMENT ONLY. for production, replace with a "publicUser" or "notLoggedInUser" or something.
uid = dn.split("=")[1].split(",")[0];
password = passwd;
}
return {
request: req,
bindUser: { uid, password }
}
}
console.log("Responding to graphql request...");
console.log(`
| User: ${req.user ? req.user.uid : "none"}
| Authorization: ${req.headers.authorization}
| Authenticated: ${req.isAuthenticated()}
`.trim());
if(req.isAuthenticated()) {
console.log("graphql API is receiving a request from an authenticated user! \\o/");
try {
uid = req.user.uid;
password = "mythe";
} catch (err) {
console.log("Error: req is authenticated, but pb when trying to extract uid from req.user. Probably user was either not serialized or not deserialized properly");
console.log(err);
}
} else {
// FOR DEVELOPMENT ONLY. for production, replace with a "publicUser" or "notLoggedInUser" or something.
uid = dn.split("=")[1].split(",")[0];
password = passwd;
const graphServer = new ApolloServer({
...schema,
context,
playground: {
settings: {
"editor.theme": "light",
"editor.cursorShape": 'line'
}
return {
schema,
graphiql: environment == 'development', // gives access to GraphiQL if req comes from browser (je crois)
context: {
request: req,
bindUser: { uid: uid, password: password }
} // accessible in every single resolver as the third argument
};
})
);
}
});
graphServer.applyMiddleware({ app });
/**
* FIN API GRAPHQL
......
extends layout.pug
block content
h1 Welcome to API server
h2 Query the database
p Hello, world! This is server talking to you live on port #{port}!
p You can query the database using the form below.
img(src="/assets/logo_sigma_large.png", width="240px", id='logo', alt="Logo sigma")
div(class="logged-in-header")
p #{userName}.
form(action="/adminview/avlogout", method="post")
button.form-control(type="submit",class="button") Déconnexion
h1 API Sigma
p Ceci est l'API de Sigma.
h2 Requêtes BDD
p Pour faire des requêtes à la BDD interne de Sigma, utilisez le formulaire ci-dessous.
form(action="/adminview/db", method="get")
div.form-group
label(for="table") Table
......@@ -12,14 +17,11 @@ block content
div.form-group
label(for="columns") Columns
input.form-control(type="search", name="columns")
button.form-control(type="submit",class="button") Recherche/<em>Search</em>
button.form-control(type="submit",class="button") Recherche
|
h2 GraphiQL and Voyager
p GraphiQL is an interactive environment to make GraphQL requests to the database.
p GraphQL Voyager is an application that displays the GraphQL schema as an actual graph.
a(class="button button-small",href="/graphql") GraphiQL
h2 GraphQL Playground
p GraphQL playground permet d'interagir avec l'API GraphQL, la tester, la débeuguer.
a(class="button button-small",href="/graphql") Playground
h2 GraphQL Voyager
p Voyager est un outil de visualisation du « graphe » derrière l'API.
a(class="button button-small",href="/voyager") Voyager
|
p Currently logged in as: #{userName}.
form(action="/adminview/avlogout", method="post")
button.form-control(type="submit",class="button") Déconnexion/<em>Logout</em>
......@@ -7,7 +7,6 @@ html(lang="en")
style
include ../css/style.css
block extraStyles
title API server - #{title}
title API Sigma - #{title}
body
block content
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment