Implement WebSocketServer Adapter (#5866)

* Implement WebSocketServerAdapter

* lint

* clean up
This commit is contained in:
Diamond Lewis
2019-07-30 09:05:41 -05:00
committed by GitHub
parent 7c8e940f53
commit 218c3499f9
10 changed files with 571 additions and 522 deletions

View File

@@ -9,26 +9,26 @@ describe('ParseWebSocket', function() {
expect(parseWebSocket.ws).toBe(ws); expect(parseWebSocket.ws).toBe(ws);
}); });
it('can handle events defined in typeMap', function() { it('can handle disconnect event', function(done) {
const ws = { const ws = {
on: jasmine.createSpy('on'), onclose: () => {},
}; };
const callback = {};
const parseWebSocket = new ParseWebSocket(ws); const parseWebSocket = new ParseWebSocket(ws);
parseWebSocket.on('disconnect', callback); parseWebSocket.on('disconnect', () => {
done();
expect(parseWebSocket.ws.on).toHaveBeenCalledWith('close', callback); });
ws.onclose();
}); });
it('can handle events which are not defined in typeMap', function() { it('can handle message event', function(done) {
const ws = { const ws = {
on: jasmine.createSpy('on'), onmessage: () => {},
}; };
const callback = {};
const parseWebSocket = new ParseWebSocket(ws); const parseWebSocket = new ParseWebSocket(ws);
parseWebSocket.on('open', callback); parseWebSocket.on('message', () => {
done();
expect(parseWebSocket.ws.on).toHaveBeenCalledWith('open', callback); });
ws.onmessage();
}); });
it('can send a message', function() { it('can send a message', function() {

View File

@@ -1,5 +1,4 @@
const ParseWebSocketServer = require('../lib/LiveQuery/ParseWebSocketServer') const { ParseWebSocketServer } = require('../lib/LiveQuery/ParseWebSocketServer');
.ParseWebSocketServer;
describe('ParseWebSocketServer', function() { describe('ParseWebSocketServer', function() {
beforeEach(function(done) { beforeEach(function(done) {
@@ -19,14 +18,14 @@ describe('ParseWebSocketServer', function() {
const parseWebSocketServer = new ParseWebSocketServer( const parseWebSocketServer = new ParseWebSocketServer(
server, server,
onConnectCallback, onConnectCallback,
5 { websocketTimeout: 5 }
).server; ).server;
const ws = { const ws = {
readyState: 0, readyState: 0,
OPEN: 0, OPEN: 0,
ping: jasmine.createSpy('ping'), ping: jasmine.createSpy('ping'),
}; };
parseWebSocketServer.emit('connection', ws); parseWebSocketServer.onConnection(ws);
// Make sure callback is called // Make sure callback is called
expect(onConnectCallback).toHaveBeenCalled(); expect(onConnectCallback).toHaveBeenCalled();

View File

@@ -0,0 +1,22 @@
/*eslint no-unused-vars: "off"*/
import { WSSAdapter } from './WSSAdapter';
const WebSocketServer = require('ws').Server;
/**
* Wrapper for ws node module
*/
export class WSAdapter extends WSSAdapter {
constructor(options: any) {
super(options);
const wss = new WebSocketServer({ server: options.server });
wss.on('listening', this.onListen);
wss.on('connection', this.onConnection);
}
onListen() {}
onConnection(ws) {}
start() {}
close() {}
}
export default WSAdapter;

View File

@@ -0,0 +1,52 @@
/*eslint no-unused-vars: "off"*/
// WebSocketServer Adapter
//
// Adapter classes must implement the following functions:
// * onListen()
// * onConnection(ws)
// * start()
// * close()
//
// Default is WSAdapter. The above functions will be binded.
/**
* @module Adapters
*/
/**
* @interface WSSAdapter
*/
export class WSSAdapter {
/**
* @param {Object} options - {http.Server|https.Server} server
*/
constructor(options) {
this.onListen = () => {}
this.onConnection = () => {}
}
// /**
// * Emitted when the underlying server has been bound.
// */
// onListen() {}
// /**
// * Emitted when the handshake is complete.
// *
// * @param {WebSocket} ws - RFC 6455 WebSocket.
// */
// onConnection(ws) {}
/**
* Initialize Connection.
*
* @param {Object} options
*/
start(options) {}
/**
* Closes server.
*/
close() {}
}
export default WSSAdapter;

View File

@@ -61,7 +61,7 @@ class ParseLiveQueryServer {
this.parseWebSocketServer = new ParseWebSocketServer( this.parseWebSocketServer = new ParseWebSocketServer(
server, server,
parseWebsocket => this._onConnect(parseWebsocket), parseWebsocket => this._onConnect(parseWebsocket),
config.websocketTimeout config
); );
// Initialize subscriber // Initialize subscriber

View File

@@ -1,9 +1,7 @@
import { loadAdapter } from '../Adapters/AdapterLoader';
import { WSAdapter } from '../Adapters/WebSocketServer/WSAdapter';
import logger from '../logger'; import logger from '../logger';
import events from 'events';
const typeMap = new Map([['disconnect', 'close']]);
const getWS = function(){
return require('ws');
};
export class ParseWebSocketServer { export class ParseWebSocketServer {
server: Object; server: Object;
@@ -11,14 +9,18 @@ export class ParseWebSocketServer {
constructor( constructor(
server: any, server: any,
onConnect: Function, onConnect: Function,
websocketTimeout: number = 10 * 1000 config
) { ) {
const WebSocketServer = getWS().Server; config.server = server;
const wss = new WebSocketServer({ server: server }); const wss = loadAdapter(
wss.on('listening', () => { config.wssAdapter,
WSAdapter,
config,
);
wss.onListen = () => {
logger.info('Parse LiveQuery Server starts running'); logger.info('Parse LiveQuery Server starts running');
}); };
wss.on('connection', ws => { wss.onConnection = (ws) => {
onConnect(new ParseWebSocket(ws)); onConnect(new ParseWebSocket(ws));
// Send ping to client periodically // Send ping to client periodically
const pingIntervalId = setInterval(() => { const pingIntervalId = setInterval(() => {
@@ -27,24 +29,29 @@ export class ParseWebSocketServer {
} else { } else {
clearInterval(pingIntervalId); clearInterval(pingIntervalId);
} }
}, websocketTimeout); }, config.websocketTimeout || 10 * 1000);
}); };
wss.start();
this.server = wss; this.server = wss;
} }
close() {
if (this.server && this.server.close) {
this.server.close();
}
}
} }
export class ParseWebSocket { export class ParseWebSocket extends events.EventEmitter {
ws: any; ws: any;
constructor(ws: any) { constructor(ws: any) {
super();
ws.onmessage = (request) => this.emit('message', request);
ws.onclose = () => this.emit('disconnect');
this.ws = ws; this.ws = ws;
} }
on(type: string, callback): void {
const wsType = typeMap.has(type) ? typeMap.get(type) : type;
this.ws.on(wsType, callback);
}
send(message: any): void { send(message: any): void {
this.ws.send(message); this.ws.send(message);
} }

View File

@@ -3,494 +3,480 @@
This code has been generated by resources/buildConfigDefinitions.js This code has been generated by resources/buildConfigDefinitions.js
Do not edit manually, but update Options/index.js Do not edit manually, but update Options/index.js
*/ */
var parsers = require('./parsers'); var parsers = require("./parsers");
module.exports.ParseServerOptions = { module.exports.ParseServerOptions = {
accountLockout: { "accountLockout": {
env: 'PARSE_SERVER_ACCOUNT_LOCKOUT', "env": "PARSE_SERVER_ACCOUNT_LOCKOUT",
help: 'account lockout policy for failed login attempts', "help": "account lockout policy for failed login attempts",
action: parsers.objectParser, "action": parsers.objectParser
}, },
allowClientClassCreation: { "allowClientClassCreation": {
env: 'PARSE_SERVER_ALLOW_CLIENT_CLASS_CREATION', "env": "PARSE_SERVER_ALLOW_CLIENT_CLASS_CREATION",
help: 'Enable (or disable) client class creation, defaults to true', "help": "Enable (or disable) client class creation, defaults to true",
action: parsers.booleanParser, "action": parsers.booleanParser,
default: true, "default": true
}, },
analyticsAdapter: { "analyticsAdapter": {
env: 'PARSE_SERVER_ANALYTICS_ADAPTER', "env": "PARSE_SERVER_ANALYTICS_ADAPTER",
help: 'Adapter module for the analytics', "help": "Adapter module for the analytics",
action: parsers.moduleOrObjectParser, "action": parsers.moduleOrObjectParser
}, },
appId: { "appId": {
env: 'PARSE_SERVER_APPLICATION_ID', "env": "PARSE_SERVER_APPLICATION_ID",
help: 'Your Parse Application ID', "help": "Your Parse Application ID",
required: true, "required": true
}, },
appName: { "appName": {
env: 'PARSE_SERVER_APP_NAME', "env": "PARSE_SERVER_APP_NAME",
help: 'Sets the app name', "help": "Sets the app name"
}, },
auth: { "auth": {
env: 'PARSE_SERVER_AUTH_PROVIDERS', "env": "PARSE_SERVER_AUTH_PROVIDERS",
help: "help": "Configuration for your authentication providers, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#oauth-and-3rd-party-authentication",
'Configuration for your authentication providers, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#oauth-and-3rd-party-authentication', "action": parsers.objectParser
action: parsers.objectParser, },
}, "cacheAdapter": {
cacheAdapter: { "env": "PARSE_SERVER_CACHE_ADAPTER",
env: 'PARSE_SERVER_CACHE_ADAPTER', "help": "Adapter module for the cache",
help: 'Adapter module for the cache', "action": parsers.moduleOrObjectParser
action: parsers.moduleOrObjectParser, },
}, "cacheMaxSize": {
cacheMaxSize: { "env": "PARSE_SERVER_CACHE_MAX_SIZE",
env: 'PARSE_SERVER_CACHE_MAX_SIZE', "help": "Sets the maximum size for the in memory cache, defaults to 10000",
help: 'Sets the maximum size for the in memory cache, defaults to 10000', "action": parsers.numberParser("cacheMaxSize"),
action: parsers.numberParser('cacheMaxSize'), "default": 10000
default: 10000, },
}, "cacheTTL": {
cacheTTL: { "env": "PARSE_SERVER_CACHE_TTL",
env: 'PARSE_SERVER_CACHE_TTL', "help": "Sets the TTL for the in memory cache (in ms), defaults to 5000 (5 seconds)",
help: "action": parsers.numberParser("cacheTTL"),
'Sets the TTL for the in memory cache (in ms), defaults to 5000 (5 seconds)', "default": 5000
action: parsers.numberParser('cacheTTL'), },
default: 5000, "clientKey": {
}, "env": "PARSE_SERVER_CLIENT_KEY",
clientKey: { "help": "Key for iOS, MacOS, tvOS clients"
env: 'PARSE_SERVER_CLIENT_KEY', },
help: 'Key for iOS, MacOS, tvOS clients', "cloud": {
}, "env": "PARSE_SERVER_CLOUD",
cloud: { "help": "Full path to your cloud code main.js"
env: 'PARSE_SERVER_CLOUD', },
help: 'Full path to your cloud code main.js', "cluster": {
}, "env": "PARSE_SERVER_CLUSTER",
cluster: { "help": "Run with cluster, optionally set the number of processes default to os.cpus().length",
env: 'PARSE_SERVER_CLUSTER', "action": parsers.numberOrBooleanParser
help: },
'Run with cluster, optionally set the number of processes default to os.cpus().length', "collectionPrefix": {
action: parsers.numberOrBooleanParser, "env": "PARSE_SERVER_COLLECTION_PREFIX",
}, "help": "A collection prefix for the classes",
collectionPrefix: { "default": ""
env: 'PARSE_SERVER_COLLECTION_PREFIX', },
help: 'A collection prefix for the classes', "customPages": {
default: '', "env": "PARSE_SERVER_CUSTOM_PAGES",
}, "help": "custom pages for password validation and reset",
customPages: { "action": parsers.objectParser,
env: 'PARSE_SERVER_CUSTOM_PAGES', "default": {}
help: 'custom pages for password validation and reset', },
action: parsers.objectParser, "databaseAdapter": {
default: {}, "env": "PARSE_SERVER_DATABASE_ADAPTER",
}, "help": "Adapter module for the database",
databaseAdapter: { "action": parsers.moduleOrObjectParser
env: 'PARSE_SERVER_DATABASE_ADAPTER', },
help: 'Adapter module for the database', "databaseOptions": {
action: parsers.moduleOrObjectParser, "env": "PARSE_SERVER_DATABASE_OPTIONS",
}, "help": "Options to pass to the mongodb client",
databaseOptions: { "action": parsers.objectParser
env: 'PARSE_SERVER_DATABASE_OPTIONS', },
help: 'Options to pass to the mongodb client', "databaseURI": {
action: parsers.objectParser, "env": "PARSE_SERVER_DATABASE_URI",
}, "help": "The full URI to your database. Supported databases are mongodb or postgres.",
databaseURI: { "required": true,
env: 'PARSE_SERVER_DATABASE_URI', "default": "mongodb://localhost:27017/parse"
help: },
'The full URI to your database. Supported databases are mongodb or postgres.', "directAccess": {
required: true, "env": "PARSE_SERVER_ENABLE_EXPERIMENTAL_DIRECT_ACCESS",
default: 'mongodb://localhost:27017/parse', "help": "Replace HTTP Interface when using JS SDK in current node runtime, defaults to false. Caution, this is an experimental feature that may not be appropriate for production.",
}, "action": parsers.booleanParser,
directAccess: { "default": false
env: 'PARSE_SERVER_ENABLE_EXPERIMENTAL_DIRECT_ACCESS', },
help: "dotNetKey": {
'Replace HTTP Interface when using JS SDK in current node runtime, defaults to false. Caution, this is an experimental feature that may not be appropriate for production.', "env": "PARSE_SERVER_DOT_NET_KEY",
action: parsers.booleanParser, "help": "Key for Unity and .Net SDK"
default: false, },
}, "emailAdapter": {
dotNetKey: { "env": "PARSE_SERVER_EMAIL_ADAPTER",
env: 'PARSE_SERVER_DOT_NET_KEY', "help": "Adapter module for email sending",
help: 'Key for Unity and .Net SDK', "action": parsers.moduleOrObjectParser
}, },
emailAdapter: { "emailVerifyTokenValidityDuration": {
env: 'PARSE_SERVER_EMAIL_ADAPTER', "env": "PARSE_SERVER_EMAIL_VERIFY_TOKEN_VALIDITY_DURATION",
help: 'Adapter module for email sending', "help": "Email verification token validity duration, in seconds",
action: parsers.moduleOrObjectParser, "action": parsers.numberParser("emailVerifyTokenValidityDuration")
}, },
emailVerifyTokenValidityDuration: { "enableAnonymousUsers": {
env: 'PARSE_SERVER_EMAIL_VERIFY_TOKEN_VALIDITY_DURATION', "env": "PARSE_SERVER_ENABLE_ANON_USERS",
help: 'Email verification token validity duration, in seconds', "help": "Enable (or disable) anon users, defaults to true",
action: parsers.numberParser('emailVerifyTokenValidityDuration'), "action": parsers.booleanParser,
}, "default": true
enableAnonymousUsers: { },
env: 'PARSE_SERVER_ENABLE_ANON_USERS', "enableExpressErrorHandler": {
help: 'Enable (or disable) anon users, defaults to true', "env": "PARSE_SERVER_ENABLE_EXPRESS_ERROR_HANDLER",
action: parsers.booleanParser, "help": "Enables the default express error handler for all errors",
default: true, "action": parsers.booleanParser,
}, "default": false
enableExpressErrorHandler: { },
env: 'PARSE_SERVER_ENABLE_EXPRESS_ERROR_HANDLER', "enableSingleSchemaCache": {
help: 'Enables the default express error handler for all errors', "env": "PARSE_SERVER_ENABLE_SINGLE_SCHEMA_CACHE",
action: parsers.booleanParser, "help": "Use a single schema cache shared across requests. Reduces number of queries made to _SCHEMA, defaults to false, i.e. unique schema cache per request.",
default: false, "action": parsers.booleanParser,
}, "default": false
enableSingleSchemaCache: { },
env: 'PARSE_SERVER_ENABLE_SINGLE_SCHEMA_CACHE', "expireInactiveSessions": {
help: "env": "PARSE_SERVER_EXPIRE_INACTIVE_SESSIONS",
'Use a single schema cache shared across requests. Reduces number of queries made to _SCHEMA, defaults to false, i.e. unique schema cache per request.', "help": "Sets wether we should expire the inactive sessions, defaults to true",
action: parsers.booleanParser, "action": parsers.booleanParser,
default: false, "default": true
}, },
expireInactiveSessions: { "fileKey": {
env: 'PARSE_SERVER_EXPIRE_INACTIVE_SESSIONS', "env": "PARSE_SERVER_FILE_KEY",
help: "help": "Key for your files"
'Sets wether we should expire the inactive sessions, defaults to true', },
action: parsers.booleanParser, "filesAdapter": {
default: true, "env": "PARSE_SERVER_FILES_ADAPTER",
}, "help": "Adapter module for the files sub-system",
fileKey: { "action": parsers.moduleOrObjectParser
env: 'PARSE_SERVER_FILE_KEY', },
help: 'Key for your files', "graphQLPath": {
}, "env": "PARSE_SERVER_GRAPHQL_PATH",
filesAdapter: { "help": "Mount path for the GraphQL endpoint, defaults to /graphql",
env: 'PARSE_SERVER_FILES_ADAPTER', "default": "/graphql"
help: 'Adapter module for the files sub-system', },
action: parsers.moduleOrObjectParser, "graphQLSchema": {
}, "env": "PARSE_SERVER_GRAPH_QLSCHEMA",
graphQLPath: { "help": "Full path to your GraphQL custom schema.graphql file"
env: 'PARSE_SERVER_GRAPHQL_PATH', },
help: 'Mount path for the GraphQL endpoint, defaults to /graphql', "host": {
default: '/graphql', "env": "PARSE_SERVER_HOST",
}, "help": "The host to serve ParseServer on, defaults to 0.0.0.0",
graphQLSchema: { "default": "0.0.0.0"
env: 'PARSE_SERVER_GRAPH_QLSCHEMA', },
help: 'Full path to your GraphQL custom schema.graphql file', "javascriptKey": {
}, "env": "PARSE_SERVER_JAVASCRIPT_KEY",
host: { "help": "Key for the Javascript SDK"
env: 'PARSE_SERVER_HOST', },
help: 'The host to serve ParseServer on, defaults to 0.0.0.0', "jsonLogs": {
default: '0.0.0.0', "env": "JSON_LOGS",
}, "help": "Log as structured JSON objects",
javascriptKey: { "action": parsers.booleanParser
env: 'PARSE_SERVER_JAVASCRIPT_KEY', },
help: 'Key for the Javascript SDK', "liveQuery": {
}, "env": "PARSE_SERVER_LIVE_QUERY",
jsonLogs: { "help": "parse-server's LiveQuery configuration object",
env: 'JSON_LOGS', "action": parsers.objectParser
help: 'Log as structured JSON objects', },
action: parsers.booleanParser, "liveQueryServerOptions": {
}, "env": "PARSE_SERVER_LIVE_QUERY_SERVER_OPTIONS",
liveQuery: { "help": "Live query server configuration options (will start the liveQuery server)",
env: 'PARSE_SERVER_LIVE_QUERY', "action": parsers.objectParser
help: "parse-server's LiveQuery configuration object", },
action: parsers.objectParser, "loggerAdapter": {
}, "env": "PARSE_SERVER_LOGGER_ADAPTER",
liveQueryServerOptions: { "help": "Adapter module for the logging sub-system",
env: 'PARSE_SERVER_LIVE_QUERY_SERVER_OPTIONS', "action": parsers.moduleOrObjectParser
help: },
'Live query server configuration options (will start the liveQuery server)', "logLevel": {
action: parsers.objectParser, "env": "PARSE_SERVER_LOG_LEVEL",
}, "help": "Sets the level for logs"
loggerAdapter: { },
env: 'PARSE_SERVER_LOGGER_ADAPTER', "logsFolder": {
help: 'Adapter module for the logging sub-system', "env": "PARSE_SERVER_LOGS_FOLDER",
action: parsers.moduleOrObjectParser, "help": "Folder for the logs (defaults to './logs'); set to null to disable file based logging",
}, "default": "./logs"
logLevel: { },
env: 'PARSE_SERVER_LOG_LEVEL', "masterKey": {
help: 'Sets the level for logs', "env": "PARSE_SERVER_MASTER_KEY",
}, "help": "Your Parse Master Key",
logsFolder: { "required": true
env: 'PARSE_SERVER_LOGS_FOLDER', },
help: "masterKeyIps": {
"Folder for the logs (defaults to './logs'); set to null to disable file based logging", "env": "PARSE_SERVER_MASTER_KEY_IPS",
default: './logs', "help": "Restrict masterKey to be used by only these ips, defaults to [] (allow all ips)",
}, "action": parsers.arrayParser,
masterKey: { "default": []
env: 'PARSE_SERVER_MASTER_KEY', },
help: 'Your Parse Master Key', "maxLimit": {
required: true, "env": "PARSE_SERVER_MAX_LIMIT",
}, "help": "Max value for limit option on queries, defaults to unlimited",
masterKeyIps: { "action": parsers.numberParser("maxLimit")
env: 'PARSE_SERVER_MASTER_KEY_IPS', },
help: "maxUploadSize": {
'Restrict masterKey to be used by only these ips, defaults to [] (allow all ips)', "env": "PARSE_SERVER_MAX_UPLOAD_SIZE",
action: parsers.arrayParser, "help": "Max file size for uploads, defaults to 20mb",
default: [], "default": "20mb"
}, },
maxLimit: { "middleware": {
env: 'PARSE_SERVER_MAX_LIMIT', "env": "PARSE_SERVER_MIDDLEWARE",
help: 'Max value for limit option on queries, defaults to unlimited', "help": "middleware for express server, can be string or function"
action: parsers.numberParser('maxLimit'), },
}, "mountGraphQL": {
maxUploadSize: { "env": "PARSE_SERVER_MOUNT_GRAPHQL",
env: 'PARSE_SERVER_MAX_UPLOAD_SIZE', "help": "Mounts the GraphQL endpoint",
help: 'Max file size for uploads, defaults to 20mb', "action": parsers.booleanParser,
default: '20mb', "default": false
}, },
middleware: { "mountPath": {
env: 'PARSE_SERVER_MIDDLEWARE', "env": "PARSE_SERVER_MOUNT_PATH",
help: 'middleware for express server, can be string or function', "help": "Mount path for the server, defaults to /parse",
}, "default": "/parse"
mountGraphQL: { },
env: 'PARSE_SERVER_MOUNT_GRAPHQL', "mountPlayground": {
help: 'Mounts the GraphQL endpoint', "env": "PARSE_SERVER_MOUNT_PLAYGROUND",
action: parsers.booleanParser, "help": "Mounts the GraphQL Playground - never use this option in production",
default: false, "action": parsers.booleanParser,
}, "default": false
mountPath: { },
env: 'PARSE_SERVER_MOUNT_PATH', "objectIdSize": {
help: 'Mount path for the server, defaults to /parse', "env": "PARSE_SERVER_OBJECT_ID_SIZE",
default: '/parse', "help": "Sets the number of characters in generated object id's, default 10",
}, "action": parsers.numberParser("objectIdSize"),
mountPlayground: { "default": 10
env: 'PARSE_SERVER_MOUNT_PLAYGROUND', },
help: 'Mounts the GraphQL Playground - never use this option in production', "passwordPolicy": {
action: parsers.booleanParser, "env": "PARSE_SERVER_PASSWORD_POLICY",
default: false, "help": "Password policy for enforcing password related rules",
}, "action": parsers.objectParser
objectIdSize: { },
env: 'PARSE_SERVER_OBJECT_ID_SIZE', "playgroundPath": {
help: "Sets the number of characters in generated object id's, default 10", "env": "PARSE_SERVER_PLAYGROUND_PATH",
action: parsers.numberParser('objectIdSize'), "help": "Mount path for the GraphQL Playground, defaults to /playground",
default: 10, "default": "/playground"
}, },
passwordPolicy: { "port": {
env: 'PARSE_SERVER_PASSWORD_POLICY', "env": "PORT",
help: 'Password policy for enforcing password related rules', "help": "The port to run the ParseServer, defaults to 1337.",
action: parsers.objectParser, "action": parsers.numberParser("port"),
}, "default": 1337
playgroundPath: { },
env: 'PARSE_SERVER_PLAYGROUND_PATH', "preserveFileName": {
help: 'Mount path for the GraphQL Playground, defaults to /playground', "env": "PARSE_SERVER_PRESERVE_FILE_NAME",
default: '/playground', "help": "Enable (or disable) the addition of a unique hash to the file names",
}, "action": parsers.booleanParser,
port: { "default": false
env: 'PORT', },
help: 'The port to run the ParseServer, defaults to 1337.', "preventLoginWithUnverifiedEmail": {
action: parsers.numberParser('port'), "env": "PARSE_SERVER_PREVENT_LOGIN_WITH_UNVERIFIED_EMAIL",
default: 1337, "help": "Prevent user from login if email is not verified and PARSE_SERVER_VERIFY_USER_EMAILS is true, defaults to false",
}, "action": parsers.booleanParser,
preserveFileName: { "default": false
env: 'PARSE_SERVER_PRESERVE_FILE_NAME', },
help: 'Enable (or disable) the addition of a unique hash to the file names', "protectedFields": {
action: parsers.booleanParser, "env": "PARSE_SERVER_PROTECTED_FIELDS",
default: false, "help": "Protected fields that should be treated with extra security when fetching details.",
}, "action": parsers.objectParser,
preventLoginWithUnverifiedEmail: { "default": {
env: 'PARSE_SERVER_PREVENT_LOGIN_WITH_UNVERIFIED_EMAIL', "_User": {
help: "*": ["email"]
'Prevent user from login if email is not verified and PARSE_SERVER_VERIFY_USER_EMAILS is true, defaults to false', }
action: parsers.booleanParser, }
default: false, },
}, "publicServerURL": {
protectedFields: { "env": "PARSE_PUBLIC_SERVER_URL",
env: 'PARSE_SERVER_PROTECTED_FIELDS', "help": "Public URL to your parse server with http:// or https://."
help: },
'Protected fields that should be treated with extra security when fetching details.', "push": {
action: parsers.objectParser, "env": "PARSE_SERVER_PUSH",
default: { "help": "Configuration for push, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#push-notifications",
_User: { "action": parsers.objectParser
'*': ['email'], },
}, "readOnlyMasterKey": {
}, "env": "PARSE_SERVER_READ_ONLY_MASTER_KEY",
}, "help": "Read-only key, which has the same capabilities as MasterKey without writes"
publicServerURL: { },
env: 'PARSE_PUBLIC_SERVER_URL', "restAPIKey": {
help: 'Public URL to your parse server with http:// or https://.', "env": "PARSE_SERVER_REST_API_KEY",
}, "help": "Key for REST calls"
push: { },
env: 'PARSE_SERVER_PUSH', "revokeSessionOnPasswordReset": {
help: "env": "PARSE_SERVER_REVOKE_SESSION_ON_PASSWORD_RESET",
'Configuration for push, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#push-notifications', "help": "When a user changes their password, either through the reset password email or while logged in, all sessions are revoked if this is true. Set to false if you don't want to revoke sessions.",
action: parsers.objectParser, "action": parsers.booleanParser,
}, "default": true
readOnlyMasterKey: { },
env: 'PARSE_SERVER_READ_ONLY_MASTER_KEY', "scheduledPush": {
help: "env": "PARSE_SERVER_SCHEDULED_PUSH",
'Read-only key, which has the same capabilities as MasterKey without writes', "help": "Configuration for push scheduling, defaults to false.",
}, "action": parsers.booleanParser,
restAPIKey: { "default": false
env: 'PARSE_SERVER_REST_API_KEY', },
help: 'Key for REST calls', "schemaCacheTTL": {
}, "env": "PARSE_SERVER_SCHEMA_CACHE_TTL",
revokeSessionOnPasswordReset: { "help": "The TTL for caching the schema for optimizing read/write operations. You should put a long TTL when your DB is in production. default to 5000; set 0 to disable.",
env: 'PARSE_SERVER_REVOKE_SESSION_ON_PASSWORD_RESET', "action": parsers.numberParser("schemaCacheTTL"),
help: "default": 5000
"When a user changes their password, either through the reset password email or while logged in, all sessions are revoked if this is true. Set to false if you don't want to revoke sessions.", },
action: parsers.booleanParser, "serverURL": {
default: true, "env": "PARSE_SERVER_URL",
}, "help": "URL to your parse server with http:// or https://.",
scheduledPush: { "required": true
env: 'PARSE_SERVER_SCHEDULED_PUSH', },
help: 'Configuration for push scheduling, defaults to false.', "sessionLength": {
action: parsers.booleanParser, "env": "PARSE_SERVER_SESSION_LENGTH",
default: false, "help": "Session duration, in seconds, defaults to 1 year",
}, "action": parsers.numberParser("sessionLength"),
schemaCacheTTL: { "default": 31536000
env: 'PARSE_SERVER_SCHEMA_CACHE_TTL', },
help: "silent": {
'The TTL for caching the schema for optimizing read/write operations. You should put a long TTL when your DB is in production. default to 5000; set 0 to disable.', "env": "SILENT",
action: parsers.numberParser('schemaCacheTTL'), "help": "Disables console output",
default: 5000, "action": parsers.booleanParser
}, },
serverURL: { "skipMongoDBServer13732Workaround": {
env: 'PARSE_SERVER_URL', "env": "PARSE_SKIP_MONGODB_SERVER_13732_WORKAROUND",
help: 'URL to your parse server with http:// or https://.', "help": "Circumvent Parse workaround for historical MongoDB bug SERVER-13732",
required: true, "action": parsers.booleanParser,
}, "default": false
sessionLength: { },
env: 'PARSE_SERVER_SESSION_LENGTH', "startLiveQueryServer": {
help: 'Session duration, in seconds, defaults to 1 year', "env": "PARSE_SERVER_START_LIVE_QUERY_SERVER",
action: parsers.numberParser('sessionLength'), "help": "Starts the liveQuery server",
default: 31536000, "action": parsers.booleanParser
}, },
silent: { "userSensitiveFields": {
env: 'SILENT', "env": "PARSE_SERVER_USER_SENSITIVE_FIELDS",
help: 'Disables console output', "help": "Personally identifiable information fields in the user table the should be removed for non-authorized users. Deprecated @see protectedFields",
action: parsers.booleanParser, "action": parsers.arrayParser
}, },
skipMongoDBServer13732Workaround: { "verbose": {
env: 'PARSE_SKIP_MONGODB_SERVER_13732_WORKAROUND', "env": "VERBOSE",
help: 'Circumvent Parse workaround for historical MongoDB bug SERVER-13732', "help": "Set the logging to verbose",
action: parsers.booleanParser, "action": parsers.booleanParser
default: false, },
}, "verifyUserEmails": {
startLiveQueryServer: { "env": "PARSE_SERVER_VERIFY_USER_EMAILS",
env: 'PARSE_SERVER_START_LIVE_QUERY_SERVER', "help": "Enable (or disable) user email validation, defaults to false",
help: 'Starts the liveQuery server', "action": parsers.booleanParser,
action: parsers.booleanParser, "default": false
}, },
userSensitiveFields: { "webhookKey": {
env: 'PARSE_SERVER_USER_SENSITIVE_FIELDS', "env": "PARSE_SERVER_WEBHOOK_KEY",
help: "help": "Key sent with outgoing webhook calls"
'Personally identifiable information fields in the user table the should be removed for non-authorized users. Deprecated @see protectedFields', }
action: parsers.arrayParser,
},
verbose: {
env: 'VERBOSE',
help: 'Set the logging to verbose',
action: parsers.booleanParser,
},
verifyUserEmails: {
env: 'PARSE_SERVER_VERIFY_USER_EMAILS',
help: 'Enable (or disable) user email validation, defaults to false',
action: parsers.booleanParser,
default: false,
},
webhookKey: {
env: 'PARSE_SERVER_WEBHOOK_KEY',
help: 'Key sent with outgoing webhook calls',
},
}; };
module.exports.CustomPagesOptions = { module.exports.CustomPagesOptions = {
choosePassword: { "choosePassword": {
env: 'PARSE_SERVER_CUSTOM_PAGES_CHOOSE_PASSWORD', "env": "PARSE_SERVER_CUSTOM_PAGES_CHOOSE_PASSWORD",
help: 'choose password page path', "help": "choose password page path"
}, },
invalidLink: { "invalidLink": {
env: 'PARSE_SERVER_CUSTOM_PAGES_INVALID_LINK', "env": "PARSE_SERVER_CUSTOM_PAGES_INVALID_LINK",
help: 'invalid link page path', "help": "invalid link page path"
}, },
invalidVerificationLink: { "invalidVerificationLink": {
env: 'PARSE_SERVER_CUSTOM_PAGES_INVALID_VERIFICATION_LINK', "env": "PARSE_SERVER_CUSTOM_PAGES_INVALID_VERIFICATION_LINK",
help: 'invalid verification link page path', "help": "invalid verification link page path"
}, },
linkSendFail: { "linkSendFail": {
env: 'PARSE_SERVER_CUSTOM_PAGES_LINK_SEND_FAIL', "env": "PARSE_SERVER_CUSTOM_PAGES_LINK_SEND_FAIL",
help: 'verification link send fail page path', "help": "verification link send fail page path"
}, },
linkSendSuccess: { "linkSendSuccess": {
env: 'PARSE_SERVER_CUSTOM_PAGES_LINK_SEND_SUCCESS', "env": "PARSE_SERVER_CUSTOM_PAGES_LINK_SEND_SUCCESS",
help: 'verification link send success page path', "help": "verification link send success page path"
}, },
parseFrameURL: { "parseFrameURL": {
env: 'PARSE_SERVER_CUSTOM_PAGES_PARSE_FRAME_URL', "env": "PARSE_SERVER_CUSTOM_PAGES_PARSE_FRAME_URL",
help: 'for masking user-facing pages', "help": "for masking user-facing pages"
}, },
passwordResetSuccess: { "passwordResetSuccess": {
env: 'PARSE_SERVER_CUSTOM_PAGES_PASSWORD_RESET_SUCCESS', "env": "PARSE_SERVER_CUSTOM_PAGES_PASSWORD_RESET_SUCCESS",
help: 'password reset success page path', "help": "password reset success page path"
},
verifyEmailSuccess: {
env: 'PARSE_SERVER_CUSTOM_PAGES_VERIFY_EMAIL_SUCCESS',
help: 'verify email success page path',
}, },
"verifyEmailSuccess": {
"env": "PARSE_SERVER_CUSTOM_PAGES_VERIFY_EMAIL_SUCCESS",
"help": "verify email success page path"
}
}; };
module.exports.LiveQueryOptions = { module.exports.LiveQueryOptions = {
classNames: { "classNames": {
env: 'PARSE_SERVER_LIVEQUERY_CLASSNAMES', "env": "PARSE_SERVER_LIVEQUERY_CLASSNAMES",
help: "parse-server's LiveQuery classNames", "help": "parse-server's LiveQuery classNames",
action: parsers.arrayParser, "action": parsers.arrayParser
}, },
pubSubAdapter: { "pubSubAdapter": {
env: 'PARSE_SERVER_LIVEQUERY_PUB_SUB_ADAPTER', "env": "PARSE_SERVER_LIVEQUERY_PUB_SUB_ADAPTER",
help: 'LiveQuery pubsub adapter', "help": "LiveQuery pubsub adapter",
action: parsers.moduleOrObjectParser, "action": parsers.moduleOrObjectParser
}, },
redisOptions: { "redisOptions": {
env: 'PARSE_SERVER_LIVEQUERY_REDIS_OPTIONS', "env": "PARSE_SERVER_LIVEQUERY_REDIS_OPTIONS",
help: "parse-server's LiveQuery redisOptions", "help": "parse-server's LiveQuery redisOptions",
action: parsers.objectParser, "action": parsers.objectParser
}, },
redisURL: { "redisURL": {
env: 'PARSE_SERVER_LIVEQUERY_REDIS_URL', "env": "PARSE_SERVER_LIVEQUERY_REDIS_URL",
help: "parse-server's LiveQuery redisURL", "help": "parse-server's LiveQuery redisURL"
}, },
"wssAdapter": {
"env": "PARSE_SERVER_LIVEQUERY_WSS_ADAPTER",
"help": "Adapter module for the WebSocketServer",
"action": parsers.moduleOrObjectParser
}
}; };
module.exports.LiveQueryServerOptions = { module.exports.LiveQueryServerOptions = {
appId: { "appId": {
env: 'PARSE_LIVE_QUERY_SERVER_APP_ID', "env": "PARSE_LIVE_QUERY_SERVER_APP_ID",
help: "help": "This string should match the appId in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same appId."
'This string should match the appId in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same appId.',
}, },
cacheTimeout: { "cacheTimeout": {
env: 'PARSE_LIVE_QUERY_SERVER_CACHE_TIMEOUT', "env": "PARSE_LIVE_QUERY_SERVER_CACHE_TIMEOUT",
help: "help": "Number in milliseconds. When clients provide the sessionToken to the LiveQuery server, the LiveQuery server will try to fetch its ParseUser's objectId from parse server and store it in the cache. The value defines the duration of the cache. Check the following Security section and our protocol specification for details, defaults to 30 * 24 * 60 * 60 * 1000 ms (~30 days).",
"Number in milliseconds. When clients provide the sessionToken to the LiveQuery server, the LiveQuery server will try to fetch its ParseUser's objectId from parse server and store it in the cache. The value defines the duration of the cache. Check the following Security section and our protocol specification for details, defaults to 30 * 24 * 60 * 60 * 1000 ms (~30 days).", "action": parsers.numberParser("cacheTimeout")
action: parsers.numberParser('cacheTimeout'),
}, },
keyPairs: { "keyPairs": {
env: 'PARSE_LIVE_QUERY_SERVER_KEY_PAIRS', "env": "PARSE_LIVE_QUERY_SERVER_KEY_PAIRS",
help: "help": "A JSON object that serves as a whitelist of keys. It is used for validating clients when they try to connect to the LiveQuery server. Check the following Security section and our protocol specification for details.",
'A JSON object that serves as a whitelist of keys. It is used for validating clients when they try to connect to the LiveQuery server. Check the following Security section and our protocol specification for details.', "action": parsers.objectParser
action: parsers.objectParser,
}, },
logLevel: { "logLevel": {
env: 'PARSE_LIVE_QUERY_SERVER_LOG_LEVEL', "env": "PARSE_LIVE_QUERY_SERVER_LOG_LEVEL",
help: "help": "This string defines the log level of the LiveQuery server. We support VERBOSE, INFO, ERROR, NONE, defaults to INFO."
'This string defines the log level of the LiveQuery server. We support VERBOSE, INFO, ERROR, NONE, defaults to INFO.',
}, },
masterKey: { "masterKey": {
env: 'PARSE_LIVE_QUERY_SERVER_MASTER_KEY', "env": "PARSE_LIVE_QUERY_SERVER_MASTER_KEY",
help: "help": "This string should match the masterKey in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same masterKey."
'This string should match the masterKey in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same masterKey.',
}, },
port: { "port": {
env: 'PARSE_LIVE_QUERY_SERVER_PORT', "env": "PARSE_LIVE_QUERY_SERVER_PORT",
help: 'The port to run the LiveQuery server, defaults to 1337.', "help": "The port to run the LiveQuery server, defaults to 1337.",
action: parsers.numberParser('port'), "action": parsers.numberParser("port"),
default: 1337, "default": 1337
}, },
pubSubAdapter: { "pubSubAdapter": {
env: 'PARSE_LIVE_QUERY_SERVER_PUB_SUB_ADAPTER', "env": "PARSE_LIVE_QUERY_SERVER_PUB_SUB_ADAPTER",
help: 'LiveQuery pubsub adapter', "help": "LiveQuery pubsub adapter",
action: parsers.moduleOrObjectParser, "action": parsers.moduleOrObjectParser
}, },
redisOptions: { "redisOptions": {
env: 'PARSE_LIVE_QUERY_SERVER_REDIS_OPTIONS', "env": "PARSE_LIVE_QUERY_SERVER_REDIS_OPTIONS",
help: "parse-server's LiveQuery redisOptions", "help": "parse-server's LiveQuery redisOptions",
action: parsers.objectParser, "action": parsers.objectParser
}, },
redisURL: { "redisURL": {
env: 'PARSE_LIVE_QUERY_SERVER_REDIS_URL', "env": "PARSE_LIVE_QUERY_SERVER_REDIS_URL",
help: "parse-server's LiveQuery redisURL", "help": "parse-server's LiveQuery redisURL"
}, },
serverURL: { "serverURL": {
env: 'PARSE_LIVE_QUERY_SERVER_SERVER_URL', "env": "PARSE_LIVE_QUERY_SERVER_SERVER_URL",
help: "help": "This string should match the serverURL in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same serverURL."
'This string should match the serverURL in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same serverURL.',
}, },
websocketTimeout: { "websocketTimeout": {
env: 'PARSE_LIVE_QUERY_SERVER_WEBSOCKET_TIMEOUT', "env": "PARSE_LIVE_QUERY_SERVER_WEBSOCKET_TIMEOUT",
help: "help": "Number of milliseconds between ping/pong frames. The WebSocket server sends ping/pong frames to the clients to keep the WebSocket alive. This value defines the interval of the ping/pong frame from the server to clients, defaults to 10 * 1000 ms (10 s).",
'Number of milliseconds between ping/pong frames. The WebSocket server sends ping/pong frames to the clients to keep the WebSocket alive. This value defines the interval of the ping/pong frame from the server to clients, defaults to 10 * 1000 ms (10 s).', "action": parsers.numberParser("websocketTimeout")
action: parsers.numberParser('websocketTimeout'),
}, },
"wssAdapter": {
"env": "PARSE_LIVE_QUERY_SERVER_WSS_ADAPTER",
"help": "Adapter module for the WebSocketServer",
"action": parsers.moduleOrObjectParser
}
}; };

View File

@@ -88,6 +88,7 @@
* @property {Adapter<PubSubAdapter>} pubSubAdapter LiveQuery pubsub adapter * @property {Adapter<PubSubAdapter>} pubSubAdapter LiveQuery pubsub adapter
* @property {Any} redisOptions parse-server's LiveQuery redisOptions * @property {Any} redisOptions parse-server's LiveQuery redisOptions
* @property {String} redisURL parse-server's LiveQuery redisURL * @property {String} redisURL parse-server's LiveQuery redisURL
* @property {Adapter<WSSAdapter>} wssAdapter Adapter module for the WebSocketServer
*/ */
/** /**
@@ -103,4 +104,6 @@
* @property {String} redisURL parse-server's LiveQuery redisURL * @property {String} redisURL parse-server's LiveQuery redisURL
* @property {String} serverURL This string should match the serverURL in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same serverURL. * @property {String} serverURL This string should match the serverURL in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same serverURL.
* @property {Number} websocketTimeout Number of milliseconds between ping/pong frames. The WebSocket server sends ping/pong frames to the clients to keep the WebSocket alive. This value defines the interval of the ping/pong frame from the server to clients, defaults to 10 * 1000 ms (10 s). * @property {Number} websocketTimeout Number of milliseconds between ping/pong frames. The WebSocket server sends ping/pong frames to the clients to keep the WebSocket alive. This value defines the interval of the ping/pong frame from the server to clients, defaults to 10 * 1000 ms (10 s).
* @property {Adapter<WSSAdapter>} wssAdapter Adapter module for the WebSocketServer
*/ */

View File

@@ -5,6 +5,7 @@ import { StorageAdapter } from '../Adapters/Storage/StorageAdapter';
import { CacheAdapter } from '../Adapters/Cache/CacheAdapter'; import { CacheAdapter } from '../Adapters/Cache/CacheAdapter';
import { MailAdapter } from '../Adapters/Email/MailAdapter'; import { MailAdapter } from '../Adapters/Email/MailAdapter';
import { PubSubAdapter } from '../Adapters/PubSub/PubSubAdapter'; import { PubSubAdapter } from '../Adapters/PubSub/PubSubAdapter';
import { WSSAdapter } from '../Adapters/WebSocketServer/WSSAdapter';
// @flow // @flow
type Adapter<T> = string | any | T; type Adapter<T> = string | any | T;
@@ -231,6 +232,8 @@ export interface LiveQueryOptions {
redisURL: ?string; redisURL: ?string;
/* LiveQuery pubsub adapter */ /* LiveQuery pubsub adapter */
pubSubAdapter: ?Adapter<PubSubAdapter>; pubSubAdapter: ?Adapter<PubSubAdapter>;
/* Adapter module for the WebSocketServer */
wssAdapter: ?Adapter<WSSAdapter>;
} }
export interface LiveQueryServerOptions { export interface LiveQueryServerOptions {
@@ -257,4 +260,6 @@ export interface LiveQueryServerOptions {
redisURL: ?string; redisURL: ?string;
/* LiveQuery pubsub adapter */ /* LiveQuery pubsub adapter */
pubSubAdapter: ?Adapter<PubSubAdapter>; pubSubAdapter: ?Adapter<PubSubAdapter>;
/* Adapter module for the WebSocketServer */
wssAdapter: ?Adapter<WSSAdapter>;
} }

View File

@@ -45,32 +45,7 @@ import { ParseGraphQLServer } from './GraphQL/ParseGraphQLServer';
addParseCloud(); addParseCloud();
// ParseServer works like a constructor of an express app. // ParseServer works like a constructor of an express app.
// The args that we understand are: // https://parseplatform.org/parse-server/api/master/ParseServerOptions.html
// "analyticsAdapter": an adapter class for analytics
// "filesAdapter": a class like GridFSBucketAdapter providing create, get,
// and delete
// "loggerAdapter": a class like WinstonLoggerAdapter providing info, error,
// and query
// "jsonLogs": log as structured JSON objects
// "databaseURI": a uri like mongodb://localhost:27017/dbname to tell us
// what database this Parse API connects to.
// "cloud": relative location to cloud code to require, or a function
// that is given an instance of Parse as a parameter. Use this instance of Parse
// to register your cloud code hooks and functions.
// "appId": the application id to host
// "masterKey": the master key for requests to this app
// "collectionPrefix": optional prefix for database collection names
// "fileKey": optional key from Parse dashboard for supporting older files
// hosted by Parse
// "clientKey": optional key from Parse dashboard
// "dotNetKey": optional key from Parse dashboard
// "restAPIKey": optional key from Parse dashboard
// "webhookKey": optional key from Parse dashboard
// "javascriptKey": optional key from Parse dashboard
// "push": optional key from configure push
// "sessionLength": optional length in seconds for how long Sessions should be valid for
// "maxLimit": optional upper bound for what can be specified for the 'limit' parameter on queries
class ParseServer { class ParseServer {
/** /**
* @constructor * @constructor