Merge pull request #11 from 8thlight/add_postgraphile_subscription
Add Postgraphile subscription exposure for price feed
This commit is contained in:
commit
a6cf173fe7
4
.gitignore
vendored
4
.gitignore
vendored
@ -1,4 +1,5 @@
|
||||
.idea
|
||||
.vscode
|
||||
test_data_dir/
|
||||
contracts/*
|
||||
environments/*.toml
|
||||
@ -7,3 +8,6 @@ vagrant*.sh
|
||||
.vagrant
|
||||
test_scripts/
|
||||
vulcanizedb
|
||||
postgraphile/build/
|
||||
postgraphile/node_modules/
|
||||
postgraphile/package-lock.json
|
||||
|
@ -0,0 +1 @@
|
||||
DROP TRIGGER notify_pricefeeds ON maker.price_feeds;
|
13
db/migrations/20180911215603_add_price_feed_trigger.up.sql
Normal file
13
db/migrations/20180911215603_add_price_feed_trigger.up.sql
Normal file
@ -0,0 +1,13 @@
|
||||
CREATE OR REPLACE FUNCTION notify_pricefeed() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
PERFORM pg_notify(
|
||||
CAST('postgraphile:price_feed' AS text),
|
||||
row_to_json(NEW)::text);
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
CREATE TRIGGER notify_pricefeeds
|
||||
AFTER INSERT ON maker.price_feeds
|
||||
FOR EACH ROW
|
||||
EXECUTE PROCEDURE notify_pricefeed();
|
@ -36,6 +36,22 @@ CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
|
||||
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
|
||||
|
||||
|
||||
--
|
||||
-- Name: notify_pricefeed(); Type: FUNCTION; Schema: public; Owner: -
|
||||
--
|
||||
|
||||
CREATE FUNCTION public.notify_pricefeed() RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
BEGIN
|
||||
PERFORM pg_notify(
|
||||
CAST('postgraphile:price_feed' AS text),
|
||||
row_to_json(NEW)::text);
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
|
||||
|
||||
SET default_tablespace = '';
|
||||
|
||||
SET default_with_oids = false;
|
||||
@ -1482,6 +1498,13 @@ CREATE INDEX tx_from_index ON public.transactions USING btree (tx_from);
|
||||
CREATE INDEX tx_to_index ON public.transactions USING btree (tx_to);
|
||||
|
||||
|
||||
--
|
||||
-- Name: price_feeds notify_pricefeeds; Type: TRIGGER; Schema: maker; Owner: -
|
||||
--
|
||||
|
||||
CREATE TRIGGER notify_pricefeeds AFTER INSERT ON maker.price_feeds FOR EACH ROW EXECUTE PROCEDURE public.notify_pricefeed();
|
||||
|
||||
|
||||
--
|
||||
-- Name: bite bite_header_id_fkey; Type: FK CONSTRAINT; Schema: maker; Owner: -
|
||||
--
|
||||
|
19
postgraphile/README.md
Normal file
19
postgraphile/README.md
Normal file
@ -0,0 +1,19 @@
|
||||
# Vulcanize GraphQL API
|
||||
|
||||
This application utilizes Postgraphile to expose GraphQL endpoints for exposure of the varied data that VulcanizeDB tracks.
|
||||
|
||||
## Building
|
||||
|
||||
*This application assumes the use of the [Yarn package manager](https://yarnpkg.com/en/). The use of npm may produce unexpected results.*
|
||||
|
||||
Install dependencies with `yarn` and execute `yarn build`. The bundle produced by Webpack will be present in `build/dist/`.
|
||||
|
||||
This application currently uses the Postgraphile supporter plugin. This plugin is present in the `vendor/` directory and is copied to `node_modules/` after installation of packages. It is a fresh checkout of the plugin as of August 31st, 2018.
|
||||
|
||||
## Running
|
||||
|
||||
Provide the built bundle to node as a runnable script: `node ./build/dist/vulcanize-postgraphile-server.js`
|
||||
|
||||
## Testing
|
||||
|
||||
Tests are executed via Jasmine with a console reporter via the `yarn test` task.
|
56
postgraphile/package.json
Normal file
56
postgraphile/package.json
Normal file
@ -0,0 +1,56 @@
|
||||
{
|
||||
"name": "vulcanizedb",
|
||||
"version": "1.0.0",
|
||||
"description": "[![Join the chat at https://gitter.im/vulcanizeio/VulcanizeDB](https://badges.gitter.im/vulcanizeio/VulcanizeDB.svg)](https://gitter.im/vulcanizeio/VulcanizeDB?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)",
|
||||
"scripts": {
|
||||
"build": "rm -rf ./build/dist && webpack --config=./webpack.config.js",
|
||||
"lint": "tslint --project ./tsconfig.json --config ./tslint.json",
|
||||
"postinstall": "rm -rf node_modules/@graphile && mkdir node_modules/@graphile && cp -R ./vendor/postgraphile-supporter/ ./node_modules/@graphile/plugin-supporter/",
|
||||
"start": "npm run build && node ./build/dist/vulcanize-postgraphile-server.js",
|
||||
"test": "rm -rf ./build/spec && tsc --build ./tsconfig.test.json && jasmine --config=./spec/support/jasmine.json",
|
||||
"test:ci": "npm run lint && npm run test"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vulcanize/vulcanizedb.git"
|
||||
},
|
||||
"author": "Vulcanize, Inc.",
|
||||
"license": "Apache-2.0",
|
||||
"bugs": {
|
||||
"url": "https://github.com/vulcanize/vulcanizedb/issues"
|
||||
},
|
||||
"homepage": "https://github.com/vulcanize/vulcanizedb",
|
||||
"dependencies": {
|
||||
"express-session": "1.15.6",
|
||||
"lodash": "4.17.10",
|
||||
"passport": "0.4.0",
|
||||
"pg-native": "3.0.0",
|
||||
"postgraphile": "4.0.0-rc.4",
|
||||
"graphql-subscriptions": "0.5.8",
|
||||
"subscriptions-transport-ws": "0.9.14",
|
||||
"toml": "2.3.3",
|
||||
"pg": "6.4.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/graphql": "^0.13.4",
|
||||
"@types/express": "4.16.0",
|
||||
"@types/express-session": "1.15.10",
|
||||
"@types/jasmine": "2.8.8",
|
||||
"@types/lodash": "4.14.116",
|
||||
"@types/node": "10.9.3",
|
||||
"@types/passport": "0.4.6",
|
||||
"awesome-typescript-loader": "5.2.0",
|
||||
"jasmine": "3.2.0",
|
||||
"jasmine-ts-console-reporter": "3.1.1",
|
||||
"source-map-loader": "0.2.4",
|
||||
"tslint": "5.11.0",
|
||||
"tslint-eslint-rules": "5.4.0",
|
||||
"typescript": "3.0.1",
|
||||
"webpack": "4.17.1",
|
||||
"webpack-cli": "3.1.0",
|
||||
"webpack-dev-server": "3.1.6"
|
||||
},
|
||||
"resolutions": {
|
||||
"pg": "6.4.2"
|
||||
}
|
||||
}
|
78
postgraphile/spec/config/parse.spec.ts
Normal file
78
postgraphile/spec/config/parse.spec.ts
Normal file
@ -0,0 +1,78 @@
|
||||
import { parseConfig } from '../../src/config/parse';
|
||||
|
||||
describe('parseConfig', () => {
|
||||
let configPath: string;
|
||||
let tomlContents: string;
|
||||
let parsedToml: object;
|
||||
let readCallback: jasmine.Spy;
|
||||
let tomlParseCallback: jasmine.Spy;
|
||||
|
||||
beforeEach(() => {
|
||||
configPath = '/example/config/path.toml';
|
||||
tomlContents = `[database]\nname = 'example_database'\n `
|
||||
+ `hostname = 'example.com'\nport = 1234`;
|
||||
|
||||
parsedToml = {
|
||||
database: {
|
||||
hostname: 'example.com',
|
||||
name: 'example_database',
|
||||
port: '1234',
|
||||
user: 'user',
|
||||
password: 'password'
|
||||
}
|
||||
};
|
||||
|
||||
readCallback = jasmine.createSpy('readCallback');
|
||||
readCallback.and.returnValue(tomlContents);
|
||||
|
||||
tomlParseCallback = jasmine.createSpy('tomlParseCallback');
|
||||
tomlParseCallback.and.returnValue(parsedToml);
|
||||
});
|
||||
|
||||
it('provides the database host', () => {
|
||||
const databaseConfig = parseConfig(
|
||||
readCallback, tomlParseCallback, configPath);
|
||||
|
||||
expect(databaseConfig.host).toEqual('postgres://user:password@example.com:1234');
|
||||
});
|
||||
|
||||
it('provides the database name', () => {
|
||||
const databaseConfig = parseConfig(
|
||||
readCallback, tomlParseCallback, configPath);
|
||||
|
||||
expect(databaseConfig.database).toEqual('example_database');
|
||||
});
|
||||
|
||||
it('handles a missing config path', () => {
|
||||
const failingCall = () =>
|
||||
parseConfig(readCallback, tomlParseCallback, '');
|
||||
|
||||
tomlParseCallback.and.returnValue({
|
||||
database: { hostname: 'example.com', name: 'example_database' }
|
||||
});
|
||||
|
||||
expect(failingCall).toThrow();
|
||||
});
|
||||
|
||||
it('handles a missing database host', () => {
|
||||
const failingCall = () =>
|
||||
parseConfig(readCallback, tomlParseCallback, configPath);
|
||||
|
||||
tomlParseCallback.and.returnValue({
|
||||
database: { hostname: '', name: 'example_database' }
|
||||
});
|
||||
|
||||
expect(failingCall).toThrow();
|
||||
});
|
||||
|
||||
it('handles a missing database name', () => {
|
||||
const failingCall = () =>
|
||||
parseConfig(readCallback, tomlParseCallback, configPath);
|
||||
|
||||
tomlParseCallback.and.returnValue({
|
||||
database: { hostname: 'example.com', name: '', port: '1234' }
|
||||
});
|
||||
|
||||
expect(failingCall).toThrow();
|
||||
});
|
||||
});
|
7
postgraphile/spec/helpers/ts_console.ts
Normal file
7
postgraphile/spec/helpers/ts_console.ts
Normal file
@ -0,0 +1,7 @@
|
||||
// NOTE (jchristie@8thlight.com) This file helps Jasmine
|
||||
// comprehend TS sourcemaps by installing a reporter
|
||||
// specifically for TypeScript
|
||||
const TSConsoleReporter = require('jasmine-ts-console-reporter');
|
||||
|
||||
jasmine.getEnv().clearReporters();
|
||||
jasmine.getEnv().addReporter(new TSConsoleReporter());
|
105
postgraphile/spec/server/config.spec.ts
Normal file
105
postgraphile/spec/server/config.spec.ts
Normal file
@ -0,0 +1,105 @@
|
||||
import { PassportStatic } from 'passport';
|
||||
|
||||
import { PostgraphileMiddleware } from '../../src/adapters/postgraphile';
|
||||
import { buildServerConfig } from '../../src/server/config';
|
||||
|
||||
import {
|
||||
DatabaseConfig,
|
||||
ServerConfig,
|
||||
ServerUtilities
|
||||
} from '../../src/server/interface';
|
||||
|
||||
describe('buildServerConfig', () => {
|
||||
let configParser: jasmine.Spy;
|
||||
let postgraphileMiddleware: PostgraphileMiddleware;
|
||||
let expressSessionHandler: jasmine.Spy;
|
||||
let passportInitializer: jasmine.Spy;
|
||||
let passportSessionHandler: jasmine.Spy;
|
||||
let serverConfig: ServerConfig;
|
||||
|
||||
let serverUtilities: ServerUtilities;
|
||||
let databaseConfig: DatabaseConfig;
|
||||
|
||||
beforeEach(() => {
|
||||
databaseConfig = { host: 'example.com', database: 'example_database' };
|
||||
|
||||
postgraphileMiddleware = jasmine
|
||||
.createSpyObj<PostgraphileMiddleware>(['call']),
|
||||
|
||||
serverUtilities = {
|
||||
pluginHook: jasmine.createSpy('pluginHook'),
|
||||
enableSubscriptions: jasmine.createSpy('enableSubscriptions'),
|
||||
express: jasmine.createSpy('express'),
|
||||
expressSession: jasmine.createSpy('expressSession'),
|
||||
httpServerFactory: jasmine.createSpy('httpServerFactory'),
|
||||
passport: jasmine.createSpyObj<PassportStatic>(['initialize', 'session']),
|
||||
postgraphile: jasmine.createSpy('postgraphile')
|
||||
};
|
||||
|
||||
const rawConfig: object = { exampleOption: 'example value' };
|
||||
|
||||
configParser = jasmine.createSpy('configParser');
|
||||
configParser.and.returnValue(rawConfig);
|
||||
|
||||
expressSessionHandler = jasmine.createSpy('expressSessionHandler');
|
||||
passportInitializer = jasmine.createSpy('passportInitializer');
|
||||
passportSessionHandler = jasmine.createSpy('passportSessionHandler');
|
||||
|
||||
(serverUtilities.postgraphile as jasmine.Spy)
|
||||
.and.returnValue(postgraphileMiddleware);
|
||||
(serverUtilities.expressSession as jasmine.Spy)
|
||||
.and.returnValue(expressSessionHandler);
|
||||
(serverUtilities.passport.initialize as jasmine.Spy)
|
||||
.and.returnValue(passportInitializer);
|
||||
(serverUtilities.passport.session as jasmine.Spy)
|
||||
.and.returnValue(passportSessionHandler);
|
||||
|
||||
serverConfig = buildServerConfig(
|
||||
serverUtilities, databaseConfig, undefined);
|
||||
});
|
||||
|
||||
it('provides the Postgraphile options', () => {
|
||||
expect(serverConfig.options).not.toBeNull();
|
||||
});
|
||||
|
||||
it('enables simple subscriptions', () => {
|
||||
expect(serverConfig.options.simpleSubscriptions).toBe(true);
|
||||
});
|
||||
|
||||
it('it adds the express session handler as the first middleware', () => {
|
||||
expect(serverConfig.options.webSocketMiddlewares[0])
|
||||
.toBe(expressSessionHandler);
|
||||
});
|
||||
|
||||
it('it adds the passport initializer as the second middleware', () => {
|
||||
expect(serverConfig.options.webSocketMiddlewares[1])
|
||||
.toBe(passportInitializer);
|
||||
});
|
||||
|
||||
it('it adds the passport session handler as the third middleware', () => {
|
||||
expect(serverConfig.options.webSocketMiddlewares[2])
|
||||
.toBe(passportSessionHandler);
|
||||
});
|
||||
|
||||
it('provides the database config to Postgraphile', () => {
|
||||
expect(serverUtilities.postgraphile).toHaveBeenCalledWith(
|
||||
`${databaseConfig.host}/${databaseConfig.database}`,
|
||||
["public", "maker"],
|
||||
jasmine.any(Object));
|
||||
});
|
||||
|
||||
it('provides the Postgraphile middleware', () => {
|
||||
expect(serverConfig.middleware).toBe(postgraphileMiddleware);
|
||||
});
|
||||
|
||||
it('sets the default server port', () => {
|
||||
expect(serverConfig.port).toEqual(3000);
|
||||
});
|
||||
|
||||
it('sets an explicit server port', () => {
|
||||
const serverConfigWithPort = buildServerConfig(
|
||||
serverUtilities, databaseConfig, '1234');
|
||||
|
||||
expect(serverConfigWithPort.port).toEqual(1234);
|
||||
});
|
||||
});
|
69
postgraphile/spec/server/runtime.spec.ts
Normal file
69
postgraphile/spec/server/runtime.spec.ts
Normal file
@ -0,0 +1,69 @@
|
||||
import { Express } from 'express';
|
||||
import { PassportStatic } from 'passport';
|
||||
import { Server } from 'http';
|
||||
|
||||
import { ServerUtilities, ServerConfig } from '../../src/server/interface';
|
||||
import { bootServer } from '../../src/server/runtime';
|
||||
import { PostgraphileMiddleware } from '../../src/adapters/postgraphile';
|
||||
|
||||
describe('bootServer', () => {
|
||||
let serverUtilities: ServerUtilities;
|
||||
let serverConfig: ServerConfig;
|
||||
let mockExpressApp: Express;
|
||||
let mockHttpServer: Server;
|
||||
|
||||
beforeEach(() => {
|
||||
serverUtilities = {
|
||||
pluginHook: jasmine.createSpy('pluginHook'),
|
||||
enableSubscriptions: jasmine.createSpy('enableSubscriptions'),
|
||||
express: jasmine.createSpy('express'),
|
||||
expressSession: jasmine.createSpy('expressSession'),
|
||||
httpServerFactory: jasmine.createSpy('httpServerFactory'),
|
||||
passport: jasmine.createSpyObj<PassportStatic>(['initialize', 'session']),
|
||||
postgraphile: jasmine.createSpy('postgraphile')
|
||||
};
|
||||
|
||||
serverConfig = {
|
||||
middleware: jasmine.createSpyObj<PostgraphileMiddleware>(['call']),
|
||||
options: {
|
||||
pluginHook: jasmine.createSpy('pluginHook'),
|
||||
simpleSubscriptions: true,
|
||||
graphiql: true,
|
||||
webSocketMiddlewares: [] },
|
||||
port: 5678
|
||||
};
|
||||
|
||||
mockExpressApp = jasmine.createSpyObj<Express>(['use']);
|
||||
(serverUtilities.express as jasmine.Spy)
|
||||
.and.returnValue(mockExpressApp);
|
||||
|
||||
mockHttpServer = jasmine.createSpyObj<Server>(['listen']);
|
||||
(serverUtilities.httpServerFactory as jasmine.Spy)
|
||||
.and.returnValue(mockHttpServer);
|
||||
|
||||
bootServer(serverUtilities, serverConfig);
|
||||
});
|
||||
|
||||
it('builds a new, Node HTTP server', () => {
|
||||
expect(serverUtilities.httpServerFactory)
|
||||
.toHaveBeenCalledWith(mockExpressApp);
|
||||
});
|
||||
|
||||
it('provides Postgraphile middleware to the Express app', () => {
|
||||
const useSpy = mockExpressApp.use as jasmine.Spy;
|
||||
expect(useSpy).toHaveBeenCalledWith(serverConfig.middleware);
|
||||
});
|
||||
|
||||
it('enahances the Node HTTP server with Postgraphile subscriptions', () => {
|
||||
expect(serverUtilities.enableSubscriptions)
|
||||
.toHaveBeenCalledWith(
|
||||
mockHttpServer,
|
||||
serverConfig.middleware,
|
||||
serverConfig.options);
|
||||
});
|
||||
|
||||
it('instructs the server to listen on the given port', () => {
|
||||
const listenSpy = mockHttpServer.listen as jasmine.Spy;
|
||||
expect(listenSpy).toHaveBeenCalledWith(serverConfig.port);
|
||||
});
|
||||
});
|
11
postgraphile/spec/support/jasmine.json
Normal file
11
postgraphile/spec/support/jasmine.json
Normal file
@ -0,0 +1,11 @@
|
||||
{
|
||||
"spec_dir": "build/spec/",
|
||||
"spec_files": [
|
||||
"**/*[sS]pec.js"
|
||||
],
|
||||
"helpers": [
|
||||
"helpers/*.js"
|
||||
],
|
||||
"stopSpecOnExpectationFailure": false,
|
||||
"random": true
|
||||
}
|
11
postgraphile/src/adapters/fs.ts
Normal file
11
postgraphile/src/adapters/fs.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { URL } from 'url';
|
||||
|
||||
export type ReadFileSyncCallback = (
|
||||
path: string | number | Buffer | URL,
|
||||
options?: { encoding?: null | undefined; flag?: string | undefined; }
|
||||
| null
|
||||
| undefined
|
||||
) => string | Buffer;
|
||||
|
||||
export type TomlParseCallback
|
||||
= (fileContents: string) => { [key: string]: { [key: string]: string } };
|
7
postgraphile/src/adapters/http.ts
Normal file
7
postgraphile/src/adapters/http.ts
Normal file
@ -0,0 +1,7 @@
|
||||
import { IncomingMessage, ServerResponse, Server } from 'http';
|
||||
|
||||
export type RequestListenerCallback
|
||||
= (request: IncomingMessage, response: ServerResponse) => void;
|
||||
|
||||
export type CreateHttpServerCallback
|
||||
= (requestListener?: RequestListenerCallback) => Server;
|
31
postgraphile/src/adapters/postgraphile.ts
Normal file
31
postgraphile/src/adapters/postgraphile.ts
Normal file
@ -0,0 +1,31 @@
|
||||
import { RequestHandler } from 'express';
|
||||
import { Server } from 'http';
|
||||
import { PluginHookFn } from 'postgraphile/build/postgraphile/pluginHook';
|
||||
|
||||
// NOTE (jchristie@8thlight.com) Shape of the middleware is not
|
||||
// currently important to this application, but if a need arises,
|
||||
// any needed shape can be assigned from a custom type here. For
|
||||
// the time being, this is a named stub to provide clarity.
|
||||
export interface PostgraphileMiddleware extends RequestHandler {}
|
||||
|
||||
export interface PostgraphileOptions {
|
||||
pluginHook: PluginHookFn,
|
||||
simpleSubscriptions: boolean;
|
||||
graphiql: boolean;
|
||||
// NOTE (jchristie@8thlight.com) Shape of the middlewares is not
|
||||
// currently important to this application, but if a need arises,
|
||||
// any needed shape can be assigned from a custom type here.
|
||||
webSocketMiddlewares: object[];
|
||||
}
|
||||
|
||||
export type PostgraphileInitCallback = (
|
||||
databaseUrl: string,
|
||||
schemas: string[],
|
||||
options: PostgraphileOptions
|
||||
) => PostgraphileMiddleware;
|
||||
|
||||
export type AddSubscriptionsCallback = (
|
||||
httpServer: Server,
|
||||
middleware: PostgraphileMiddleware,
|
||||
options: PostgraphileOptions
|
||||
) => void;
|
20
postgraphile/src/adapters/session.ts
Normal file
20
postgraphile/src/adapters/session.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { SessionOptions } from 'express-session';
|
||||
import { Express, RequestHandler, Handler } from 'express';
|
||||
|
||||
export type ExpressInitCallback = () => Express;
|
||||
|
||||
export type ExpressSessionInitCallback
|
||||
= (options?: SessionOptions) => RequestHandler ;
|
||||
|
||||
export type PassportInitCallback = (
|
||||
options?: { userProperty: string; } | undefined
|
||||
) => Handler;
|
||||
|
||||
export type PassportSessionCallback = (
|
||||
options?: { pauseStream: boolean; } | undefined
|
||||
) => Handler;
|
||||
|
||||
export interface StaticPassportProvider {
|
||||
initialize: PassportInitCallback;
|
||||
session: PassportSessionCallback;
|
||||
}
|
39
postgraphile/src/config/parse.ts
Normal file
39
postgraphile/src/config/parse.ts
Normal file
@ -0,0 +1,39 @@
|
||||
import { CONFIG_PATH_KEY } from '../server/config';
|
||||
import { DatabaseConfig } from '../server/interface';
|
||||
import { ReadFileSyncCallback, TomlParseCallback } from '../adapters/fs';
|
||||
|
||||
export const MISSING_PATH_MESSAGE = `No path to config toml file provided, `
|
||||
+ `please check the value of ${CONFIG_PATH_KEY} in your environment`;
|
||||
|
||||
export const MISSING_HOST_MESSAGE = 'No database host provided in config toml';
|
||||
export const MISSING_DATABASE_MESSAGE = 'No database name provided in config '
|
||||
+ 'toml';
|
||||
|
||||
export function parseConfig(
|
||||
readCallback: ReadFileSyncCallback,
|
||||
tomlParseCallback: TomlParseCallback,
|
||||
configPath?: string
|
||||
): DatabaseConfig {
|
||||
if (!configPath || configPath.length < 1) {
|
||||
throw new Error(MISSING_PATH_MESSAGE);
|
||||
}
|
||||
|
||||
const tomlContents = readCallback(`${configPath}`).toString();
|
||||
const parsedToml = tomlParseCallback(tomlContents);
|
||||
|
||||
const host = parsedToml['database']['hostname'];
|
||||
const port = parsedToml['database']['port'];
|
||||
const database = parsedToml['database']['name'];
|
||||
const user = parsedToml['database']['user'] || '';
|
||||
const password = parsedToml['database']['password'] || '';
|
||||
|
||||
if (!host || host.length < 1) {
|
||||
throw new Error(MISSING_HOST_MESSAGE);
|
||||
}
|
||||
|
||||
if (!database || database.length < 1) {
|
||||
throw new Error(MISSING_DATABASE_MESSAGE);
|
||||
}
|
||||
|
||||
return { host: `postgres://${user}:${password}@${host}:${port}`, database };
|
||||
}
|
43
postgraphile/src/index.ts
Normal file
43
postgraphile/src/index.ts
Normal file
@ -0,0 +1,43 @@
|
||||
import { createServer } from 'http';
|
||||
import { postgraphile, makePluginHook } from 'postgraphile';
|
||||
import { readFileSync } from 'fs';
|
||||
|
||||
import express = require('express');
|
||||
import passport = require('passport');
|
||||
import session = require('express-session');
|
||||
import toml = require('toml');
|
||||
|
||||
const {
|
||||
default: PostGraphileSupporter,
|
||||
enhanceHttpServerWithSubscriptions,
|
||||
} = require('@graphile/plugin-supporter');
|
||||
const pluginHook = makePluginHook([PostGraphileSupporter]);
|
||||
|
||||
import { ServerUtilities } from './server/interface';
|
||||
import { bootServer } from './server/runtime';
|
||||
import { parseConfig } from './config/parse';
|
||||
|
||||
import {
|
||||
buildServerConfig,
|
||||
CONFIG_PATH_KEY,
|
||||
SERVER_PORT_KEY
|
||||
} from './server/config';
|
||||
|
||||
const configPath = process.env[CONFIG_PATH_KEY];
|
||||
const serverPort = process.env[SERVER_PORT_KEY];
|
||||
|
||||
const serverUtilities: ServerUtilities = {
|
||||
enableSubscriptions: enhanceHttpServerWithSubscriptions,
|
||||
express,
|
||||
expressSession: session,
|
||||
httpServerFactory: createServer,
|
||||
passport,
|
||||
postgraphile,
|
||||
pluginHook
|
||||
};
|
||||
|
||||
const databaseConfig = parseConfig(readFileSync, toml.parse, configPath);
|
||||
const serverConfig = buildServerConfig(
|
||||
serverUtilities, databaseConfig, serverPort);
|
||||
|
||||
bootServer(serverUtilities, serverConfig);
|
45
postgraphile/src/server/config.ts
Normal file
45
postgraphile/src/server/config.ts
Normal file
@ -0,0 +1,45 @@
|
||||
import { ServerUtilities, DatabaseConfig, ServerConfig } from './interface';
|
||||
|
||||
import {
|
||||
PostgraphileMiddleware,
|
||||
PostgraphileOptions
|
||||
} from '../adapters/postgraphile';
|
||||
|
||||
export const CONFIG_PATH_KEY = 'CONFIG_PATH';
|
||||
export const SERVER_PORT_KEY = 'SERVER_PORT';
|
||||
|
||||
const DEFAULT_SERVER_PORT = '3000';
|
||||
|
||||
export function buildServerConfig(
|
||||
utilities: ServerUtilities,
|
||||
databaseConfig: DatabaseConfig,
|
||||
port?: string
|
||||
): ServerConfig {
|
||||
if (!port || port.length < 1) {
|
||||
port = DEFAULT_SERVER_PORT;
|
||||
}
|
||||
|
||||
const expressSessionHandler = utilities.expressSession();
|
||||
const passportInitializer = utilities.passport.initialize();
|
||||
const passportSessionHandler = utilities.passport.session();
|
||||
const pluginHook = utilities.pluginHook;
|
||||
|
||||
const options: PostgraphileOptions = {
|
||||
pluginHook: pluginHook,
|
||||
simpleSubscriptions: true,
|
||||
graphiql: true,
|
||||
webSocketMiddlewares: [
|
||||
expressSessionHandler,
|
||||
passportInitializer,
|
||||
passportSessionHandler
|
||||
]
|
||||
};
|
||||
|
||||
const middleware: PostgraphileMiddleware = utilities.postgraphile(
|
||||
`${databaseConfig.host}/${databaseConfig.database}`,
|
||||
["public", "maker"],
|
||||
options
|
||||
);
|
||||
|
||||
return { middleware, options, port: parseInt(port, 10) };
|
||||
}
|
36
postgraphile/src/server/interface.ts
Normal file
36
postgraphile/src/server/interface.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import { CreateHttpServerCallback } from '../adapters/http';
|
||||
|
||||
import {
|
||||
ExpressInitCallback,
|
||||
ExpressSessionInitCallback,
|
||||
StaticPassportProvider
|
||||
} from '../adapters/session';
|
||||
|
||||
import {
|
||||
AddSubscriptionsCallback,
|
||||
PostgraphileInitCallback,
|
||||
PostgraphileMiddleware,
|
||||
PostgraphileOptions
|
||||
} from '../adapters/postgraphile';
|
||||
import { PluginHookFn } from 'postgraphile/build/postgraphile/pluginHook';
|
||||
|
||||
export interface DatabaseConfig {
|
||||
host: string;
|
||||
database: string;
|
||||
}
|
||||
|
||||
export interface ServerConfig {
|
||||
middleware: PostgraphileMiddleware;
|
||||
options: PostgraphileOptions;
|
||||
port: number;
|
||||
}
|
||||
|
||||
export interface ServerUtilities {
|
||||
enableSubscriptions: AddSubscriptionsCallback;
|
||||
express: ExpressInitCallback;
|
||||
expressSession: ExpressSessionInitCallback;
|
||||
httpServerFactory: CreateHttpServerCallback;
|
||||
passport: StaticPassportProvider;
|
||||
postgraphile: PostgraphileInitCallback;
|
||||
pluginHook: PluginHookFn
|
||||
}
|
18
postgraphile/src/server/runtime.ts
Normal file
18
postgraphile/src/server/runtime.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { ServerUtilities, ServerConfig } from './interface';
|
||||
|
||||
export function bootServer(
|
||||
utilities: ServerUtilities,
|
||||
config: ServerConfig
|
||||
): void {
|
||||
const expressApp = utilities.express();
|
||||
expressApp.use(config.middleware);
|
||||
|
||||
const httpServer = utilities.httpServerFactory(expressApp);
|
||||
|
||||
utilities.enableSubscriptions(
|
||||
httpServer,
|
||||
config.middleware,
|
||||
config.options);
|
||||
|
||||
httpServer.listen(config.port);
|
||||
}
|
54
postgraphile/tsconfig.json
Normal file
54
postgraphile/tsconfig.json
Normal file
@ -0,0 +1,54 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Basic Options */
|
||||
"target": "es2017", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
|
||||
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
|
||||
"lib": ["esnext"], /* Specify library files to be included in the compilation: */
|
||||
// "allowJs": true, /* Allow javascript files to be compiled. */
|
||||
// "checkJs": true, /* Report errors in .js files. */
|
||||
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
|
||||
// "declaration": true, /* Generates corresponding '.d.ts' file. */
|
||||
"sourceMap": true, /* Generates corresponding '.map' file. */
|
||||
// "outFile": "./", /* Concatenate and emit output to single file. */
|
||||
"outDir": "build/dist", /* Redirect output structure to the directory. */
|
||||
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
|
||||
"removeComments": true, /* Do not emit comments to output. */
|
||||
// "noEmit": true, /* Do not emit outputs. */
|
||||
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
|
||||
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
|
||||
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
|
||||
|
||||
/* Strict Type-Checking Options */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* Enable strict null checks. */
|
||||
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
|
||||
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
|
||||
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
|
||||
|
||||
/* Additional Checks */
|
||||
// "noUnusedLocals": true, /* Report errors on unused locals. */
|
||||
// "noUnusedParameters": true, /* Report errors on unused parameters. */
|
||||
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
|
||||
|
||||
/* Module Resolution Options */
|
||||
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
|
||||
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
|
||||
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
|
||||
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
|
||||
// "typeRoots": [], /* List of folders to include type definitions from. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
|
||||
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
|
||||
|
||||
/* Source Map Options */
|
||||
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
|
||||
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
|
||||
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
|
||||
|
||||
/* Experimental Options */
|
||||
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
|
||||
}
|
||||
}
|
54
postgraphile/tsconfig.test.json
Normal file
54
postgraphile/tsconfig.test.json
Normal file
@ -0,0 +1,54 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Basic Options */
|
||||
"target": "es2017", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
|
||||
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
|
||||
"lib": ["esnext"], /* Specify library files to be included in the compilation: */
|
||||
// "allowJs": true, /* Allow javascript files to be compiled. */
|
||||
// "checkJs": true, /* Report errors in .js files. */
|
||||
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
|
||||
// "declaration": true, /* Generates corresponding '.d.ts' file. */
|
||||
"sourceMap": true, /* Generates corresponding '.map' file. */
|
||||
// "outFile": "./", /* Concatenate and emit output to single file. */
|
||||
"outDir": "build/spec", /* Redirect output structure to the directory. */
|
||||
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
|
||||
"removeComments": true, /* Do not emit comments to output. */
|
||||
// "noEmit": true, /* Do not emit outputs. */
|
||||
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
|
||||
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
|
||||
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
|
||||
|
||||
/* Strict Type-Checking Options */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* Enable strict null checks. */
|
||||
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
|
||||
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
|
||||
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
|
||||
|
||||
/* Additional Checks */
|
||||
// "noUnusedLocals": true, /* Report errors on unused locals. */
|
||||
// "noUnusedParameters": true, /* Report errors on unused parameters. */
|
||||
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
|
||||
|
||||
/* Module Resolution Options */
|
||||
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
|
||||
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
|
||||
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
|
||||
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
|
||||
// "typeRoots": [], /* List of folders to include type definitions from. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
|
||||
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
|
||||
|
||||
/* Source Map Options */
|
||||
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
|
||||
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
|
||||
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
|
||||
|
||||
/* Experimental Options */
|
||||
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
|
||||
}
|
||||
}
|
93
postgraphile/tslint.json
Normal file
93
postgraphile/tslint.json
Normal file
@ -0,0 +1,93 @@
|
||||
{
|
||||
"extends": [
|
||||
"tslint-eslint-rules"
|
||||
],
|
||||
"rules": {
|
||||
"object-curly-spacing": true,
|
||||
"ter-indent": [true, 2],
|
||||
"array-bracket-spacing": ["error", "never"],
|
||||
"class-name": true,
|
||||
"comment-format": [
|
||||
true,
|
||||
"check-space"
|
||||
],
|
||||
"curly": [true, "ignore-same-line"],
|
||||
"eofline": true,
|
||||
"forin": true,
|
||||
"indent": [
|
||||
true,
|
||||
"spaces"
|
||||
],
|
||||
"label-position": true,
|
||||
"max-line-length": [
|
||||
true,
|
||||
80
|
||||
],
|
||||
"member-access": [true, "no-public"],
|
||||
"member-ordering": [true, { "order": "statics-first" }],
|
||||
"no-arg": true,
|
||||
"no-bitwise": true,
|
||||
"no-console": [
|
||||
true,
|
||||
"debug",
|
||||
"info",
|
||||
"time",
|
||||
"timeEnd",
|
||||
"trace"
|
||||
],
|
||||
"no-consecutive-blank-lines": true,
|
||||
"no-construct": true,
|
||||
"no-debugger": true,
|
||||
"no-duplicate-variable": true,
|
||||
"no-empty": false,
|
||||
"no-eval": true,
|
||||
"no-inferrable-types": true,
|
||||
"no-shadowed-variable": false,
|
||||
"no-string-literal": false,
|
||||
"no-switch-case-fall-through": true,
|
||||
"no-trailing-whitespace": false,
|
||||
"no-unused-expression": false,
|
||||
"no-use-before-declare": true,
|
||||
"no-var-keyword": false,
|
||||
"object-literal-sort-keys": false,
|
||||
"one-line": [
|
||||
true,
|
||||
"check-open-brace",
|
||||
"check-whitespace"
|
||||
],
|
||||
"quotemark": [
|
||||
true,
|
||||
"single"
|
||||
],
|
||||
"radix": true,
|
||||
"semicolon": true,
|
||||
"triple-equals": [
|
||||
true,
|
||||
"allow-null-check"
|
||||
],
|
||||
"typedef-whitespace": [
|
||||
true,
|
||||
{
|
||||
"call-signature": "nospace",
|
||||
"index-signature": "nospace",
|
||||
"parameter": "nospace",
|
||||
"property-declaration": "nospace",
|
||||
"variable-declaration": "nospace"
|
||||
}
|
||||
],
|
||||
"variable-name": false,
|
||||
"whitespace": [
|
||||
true,
|
||||
"check-branch",
|
||||
"check-decl",
|
||||
"check-operator",
|
||||
"check-separator",
|
||||
"check-type"
|
||||
],
|
||||
|
||||
"use-host-property-decorator": false,
|
||||
"no-access-missing-member": false,
|
||||
"templates-use-public": false,
|
||||
"brace-style": false
|
||||
}
|
||||
}
|
20
postgraphile/webpack.config.js
Normal file
20
postgraphile/webpack.config.js
Normal file
@ -0,0 +1,20 @@
|
||||
module.exports = {
|
||||
entry: "./src/index.ts",
|
||||
mode: "production",
|
||||
devtool: "source-map",
|
||||
target: 'node',
|
||||
output: {
|
||||
filename: "vulcanize-postgraphile-server.js",
|
||||
path: __dirname + "/build/dist/",
|
||||
publicPath: "build/dist/"
|
||||
},
|
||||
resolve: {
|
||||
extensions: [".ts", ".tsx", ".mjs", ".js", ".json", ".css", ".png"]
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{ test: /\.ts$/, loader: "awesome-typescript-loader" },
|
||||
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
|
||||
]
|
||||
}
|
||||
};
|
4328
postgraphile/yarn.lock
Normal file
4328
postgraphile/yarn.lock
Normal file
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue
Block a user