Skip to content

Commit

Permalink
Enhancement/issue 278 graphql plugin (#487)
Browse files Browse the repository at this point in the history
* init commit of WIP with server and graphiql working

* WIP client side implementation

* output message when processing a commonjs file

* debug statement

* custom graphql client

* restore graphQL to shelf

* refactor shelf

* rollup bundling working

* graphql working in production build

* upgrade backend apollo 3

* move and re-enable data unit tests

* align server start usage with develop command

* fixed bug with dangling commas in es-modules-shims

* add new config query test case

* tests for menu query for navigation

* clean up

* add support for children query aliasing

* children query specs

* cleanup

* graph query test cases and support

* delete old cases

* console cleanup

* fix label confusion and restore id

* remove frontmatter

* refactoring and promisifying

* graph test with custom frontmatter

* restore docs

* remove example config query

* delete commented out code
  • Loading branch information
thescientist13 committed Apr 3, 2021
1 parent e565e5e commit 0bbefa8
Show file tree
Hide file tree
Showing 82 changed files with 5,091 additions and 1,172 deletions.
3 changes: 1 addition & 2 deletions .mocharc.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const path = require('path');

module.exports = {
// TODO spec: path.join(__dirname, 'packages/**/test/**/**/**/*.spec.js'),
spec: path.join(__dirname, 'packages/**/test/cases/**/**/*.spec.js'),
spec: path.join(__dirname, 'packages/**/test/**/**/**/*.spec.js'),
timeout: 30000
};
4 changes: 4 additions & 0 deletions greenwood.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const path = require('path');
// const pluginImportCommonjs = require('./packages/plugin-import-commonjs/src/index');
const pluginGoogleAnalytics = require('./packages/plugin-google-analytics/src/index');
const pluginGraphQL = require('./packages/plugin-graphql/src/index');
const pluginImportCss = require('./packages/plugin-import-css/src/index');
const pluginPolyfills = require('./packages/plugin-polyfills/src/index');
const pluginPostCss = require('./packages/plugin-postcss/src/index');
Expand All @@ -23,9 +25,11 @@ module.exports = {
{ name: 'google-site-verification', content: '4rYd8k5aFD0jDnN0CCFgUXNe4eakLP4NnA18mNnK5P0' }
],
plugins: [
// ...pluginImportCommonjs(),
pluginGoogleAnalytics({
analyticsId: 'UA-147204327-1'
}),
...pluginGraphQL(),
pluginPolyfills(),
pluginPostCss(),
...pluginImportCss()
Expand Down
44 changes: 33 additions & 11 deletions packages/cli/src/commands/build.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
const bundleCompilation = require('../lifecycles/bundle');
const copyAssets = require('../lifecycles/copy');
const { devServer } = require('../lifecycles/serve');
const fs = require('fs');
const generateCompilation = require('../lifecycles/compile');
const serializeCompilation = require('../lifecycles/serialize');
const { devServer } = require('../lifecycles/serve');
const { ServerInterface } = require('../lib/server-interface');

module.exports = runProductionBuild = async () => {

Expand All @@ -14,17 +15,38 @@ module.exports = runProductionBuild = async () => {
const port = compilation.config.devServer.port;
const outputDir = compilation.context.outputDir;

devServer(compilation).listen(port);

if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}

await serializeCompilation(compilation);
await bundleCompilation(compilation);
await copyAssets(compilation);
devServer(compilation).listen(port, async () => {
console.info(`Started local development server at localhost:${port}`);

// custom user server plugins
const servers = [...compilation.config.plugins.filter((plugin) => {
return plugin.type === 'server';
}).map((plugin) => {
const provider = plugin.provider(compilation);

if (!(provider instanceof ServerInterface)) {
console.warn(`WARNING: ${plugin.name}'s provider is not an instance of ServerInterface.`);
}

return provider;
})];

await Promise.all(servers.map(async (server) => {
server.start();

return Promise.resolve(server);
}));

if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}

await serializeCompilation(compilation);
await bundleCompilation(compilation);
await copyAssets(compilation);

resolve();
resolve();
});
} catch (err) {
reject(err);
}
Expand Down
17 changes: 9 additions & 8 deletions packages/cli/src/config/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,16 +116,17 @@ function greenwoodHtmlPlugin(compilation) {
case '.html':
return Promise.resolve('');
default:
customResources.filter((resource) => {
const shouldServe = Promise.resolve(resource.shouldServe(id));
const resourceHandler = (await Promise.all(customResources.map(async (resource) => {
const shouldServe = await resource.shouldServe(id);

if (shouldServe) {
return resource;
}
});
return shouldServe
? resource
: null;
}))).filter(resource => resource);

if (customResources.length) {
const response = await customResources[0].serve(id);
// TODO should reduce here instead
if (resourceHandler.length) {
const response = await resourceHandler[0].serve(id);

return Promise.resolve(response.body);
}
Expand Down
46 changes: 0 additions & 46 deletions packages/cli/src/data/common.js

This file was deleted.

10 changes: 0 additions & 10 deletions packages/cli/src/data/queries/children.gql

This file was deleted.

10 changes: 0 additions & 10 deletions packages/cli/src/data/queries/graph.gql

This file was deleted.

2 changes: 1 addition & 1 deletion packages/cli/src/lifecycles/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ let defaultConfig = {
devServer: {
port: 1984
},
// TODO optimization: 'spa',
optimization: '',
title: 'My App',
meta: [],
plugins: [],
Expand Down
12 changes: 9 additions & 3 deletions packages/cli/src/lifecycles/graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ module.exports = generateGraph = async (compilation) => {
const relativeWorkspacePath = directory.replace(process.cwd(), '').replace('/', '');
const template = attributes.template || 'page';
const title = attributes.title || compilation.config.title || '';
const label = attributes.label || filename.split('/')[filename.split('/').length - 1].replace('.md', '').replace('.html', '');
const id = attributes.label || filename.split('/')[filename.split('/').length - 1].replace('.md', '').replace('.html', '');
const label = id.split('-')
.map((idPart) => {
return `${idPart.charAt(0).toUpperCase()}${idPart.substring(1)}`;
}).join(' ');
let route = relativePagePath.replace('.md', '').replace('.html', '');

/*
Expand All @@ -37,7 +41,7 @@ module.exports = generateGraph = async (compilation) => {
*/
if (relativePagePath.lastIndexOf('/') > 0) {
// https://github.com/ProjectEvergreen/greenwood/issues/455
route = label === 'index' || route.replace('/index', '') === `/${label}`
route = id === 'index' || route.replace('/index', '') === `/${id}`
? route.replace('index', '')
: `${route}/`;
} else {
Expand Down Expand Up @@ -91,7 +95,8 @@ module.exports = generateGraph = async (compilation) => {
*----------------------
* data: custom page frontmatter
* filename: name of the file
* label: text representation of the filename
* id: filename without the extension
* label: "pretty" text representation of the filename
* path: path to the file relative to the workspace
* route: URL route for a given page on outputFilePath
* template: page template to use as a base for a generated component
Expand All @@ -100,6 +105,7 @@ module.exports = generateGraph = async (compilation) => {
pages.push({
data: customData || {},
filename,
id,
label,
path: route === '/' || relativePagePath.lastIndexOf('/') === 0
? `${relativeWorkspacePath}${filename}`
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/lifecycles/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ function getProdServer(compilation) {
}

if (url.endsWith('.json')) {
const contents = await fs.promises.readFile(path.join(outputDir, 'graph.json'), 'utf-8');
const contents = await fs.promises.readFile(path.join(outputDir, url), 'utf-8');

ctx.set('Content-Type', 'application/json');
ctx.body = JSON.parse(contents);
Expand Down
9 changes: 8 additions & 1 deletion packages/cli/src/plugins/resource/plugin-node-modules.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,14 @@ class NodeModulesResource extends ResourceInterface {
async serve(url) {
return new Promise(async(resolve, reject) => {
try {
const fullUrl = path.extname(url) === '' ? `${url}.js` : url;
const fullUrl = path.extname(url) === ''
? `${url}.js`
: url;
// const fullUrl = path.extname(url) === ''
// ? fs.existsSync(`${url}.mjs`) // test for .mjs first
// ? `${url}.mjs`
// : `${url}.js`
// : url;
const body = await fs.promises.readFile(fullUrl);

resolve({
Expand Down
7 changes: 4 additions & 3 deletions packages/cli/src/plugins/server/plugin-livereload.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const livereload = require('livereload');
const path = require('path');
const { ResourceInterface } = require('../../lib/resource-interface');
const { ServerInterface } = require('../../lib/server-interface');

Expand All @@ -25,8 +24,10 @@ class LiveReloadServer extends ServerInterface {

class LiveReloadResource extends ResourceInterface {

async shouldIntercept(url) {
return Promise.resolve(path.extname(url) === '' && process.env.__GWD_COMMAND__ === 'develop'); // eslint-disable-line no-underscore-dangle
async shouldIntercept(url, body, headers) {
const { accept } = headers.request;

return Promise.resolve(accept && accept.indexOf('text/html') >= 0 && process.env.__GWD_COMMAND__ === 'develop'); // eslint-disable-line no-underscore-dangle
}

async intercept(url, body) {
Expand Down
Loading

0 comments on commit 0bbefa8

Please sign in to comment.