Merge Complete

This commit is contained in:
Luis Fernando Molina committed 2020-11-20 20:28:04 +01:00
1 parent 482ef7a81a
commit dabe23d505
6483 files changed

No files matched your search

@@ -0,0 +1,12 @@
# Ignore files to be uploaded to the image
.env*
.git
.gitignore
Dockerfile
Dockerfile.prod
README.md
CODE_OF_CONDUCT.md
CONTRIBUTING.md
/coverage
/.nyc_output
@@ -0,0 +1,26 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules/
# Optional npm cache directory
.npm
# dotenv environment variables file
.env*
# Build folder js files
build/
dist/
# Visual Studio Code
.vscode
# Mac specific files
.DS_Store
# JetBrains
.idea
@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at feedback at superalgos dot org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
@@ -0,0 +1,51 @@
# Contributing
We are thrilled you are interested in contributing to the this module. Your help may be essential to the project's success and we want you in!
Superalgos.org is an open source project, currently at a very early stage. Although this module is not open source software yet, we do welcome contributions from the community.
Contributions are deemed _work for hire_ and --as such-- are compensated on a case by case basis, with ALGO tokens. Contributors agree to provide an express grant of patent rights for their contributions. Our Balanced Contributor Intellectual Property Agreement is a direct implementation of GitHub's [Balanced Employee Intellectual Property Agreement 1.0.1](https://github.com/github/balanced-employee-ip-agreement/blob/master/Balanced_Employee_IP_Agreement.md).
# Balanced Contributor Intellectual Property Agreement 1.0.1
This BALANCED CONTRIBUTOR INTELLECTUAL PROPERTY AGREEMENT is between person named below and Superalgos ("Company").
**What is this?** This is the Company's Intellectual Property Agreement ("Agreement"). If you've worked in the technology space before, there's a good chance that you've run across one or more of these in the past. This document is the official, entire and exclusive agreement on what intellectual property ("IP") is yours, and what belongs to the Company.
**Why is this?** The Company needs to be clear on what IP it owns and has rights to. Its customers, contributors, and investors depend on the Company having the legal rights to the products and services it is providing so that the Company can continue operating and doing business.
The Company also believes that it's important to be clear on what it doesn't own. The Company doesn't want you looking over your shoulder every time you work on something personal or worrying that the Company will someday seize your open source non-lethal mousetrap simulation software. In other words, the Company isn't interested in appropriating your personal projects.
**Read this.** Please read this document and be sure you understand it before you sign it. Due to legal risk and corporate obligations, the Company cannot, by and large, negotiate its terms. If you feel you have a particular circumstance that keeps you from signing, please let the Company's legal department ("Legal") know. And, of course, you're always free and encouraged to get your own legal counsel to explain anything you're not clear on.
Cool? Then, by signing this Agreement, and as a condition of your contribution, you agree to the following:
1. **What the Company owns.** The Company owns any IP ("Company IP") that you create, or help create _as its contributor or contractor_, but only if it meets one or more of these additional conditions: The IP was (i) related to an existing or prospective Company product or service at the time you developed, invented, or created it, (ii) developed for use by the Company, or (iii) developed or promoted with existing Company IP or with the Company's endorsement. You hereby grant and assign, and will grant and assign, to the Company all rights and interests in all Company IP.
"Company IP" includes concepts, designs, developments, discoveries, ideas, improvements, inventions, trade secrets, trademarks, and works of authorship.
2. **What the Company doesn't own.** If you create IP that doesn't fit into one of the categories listed above, the Company doesn't own it. In other words, the Company doesn't own concepts, designs, developments, discoveries, ideas, improvements, inventions, trade secrets, trademarks, or works of authorship that you develop, invent, or create that do not meet any of the conditions in Section 1. This is true regardless of the computer you use to develop your IP, including the one furnished to you by the Company.
3. **Contribution of your IP to Company projects.** If you include your own IP – such as IP you created prior to working for the Company – into a Company product or service, it's still yours, of course, but you grant the Company a non-exclusive, irrevocable, fully paid-up, royalty-free, perpetual, sublicensable, transferable, worldwide license to use it without restriction in any way or implementation, in modified form, or as is, by itself, or incorporated into another product or service ("License"). If you include your name in any project over which the Company would have rights under this Agreement, such as in a copyright notice or a comment in code or documentation, then the License covers the rights associated with that use of your name as well.
4. **Your contributions to non-Company projects.** The Company recognizes that you may be engaged in work that requires you to submit IP to entities other than the Company, such as open source projects used by the Company. Please make sure that Legal is aware of what you're working on so that Legal can help with any licensing issues. If any project asks you to sign a contribution agreement, you should check with Legal before doing so. These agreements may be legally binding on the Company and so should be run through Legal first.
5. **Works made for hire.** All Company IP that you are involved with or create as part of your work for the Company is [work made for hire](http://www.copyright.gov/circs/circ09.pdf) under copyright law and compensated by your regular salary or pay.
6. **No conflicts.** You agree that you don't have any outstanding agreements or obligations that conflict with those in this Agreement, and that you won't enter into conflicting agreements in the future.
7. **IP protection.** The Company might someday need to show the work that went into the development of IP that it uses or has used, or to make government filings to establish that it owns the IP or has rights over it. To help in those situations, you agree not to destroy any records you maintain relating to the development of any Company IP or IP under License (together, "All IP"), and, if the Company asks, to provide those records to the Company. You agree to help the Company secure and defend its rights in All IP, including after you leave the Company. For your help the Company will compensate you at a reasonable rate. If the Company is unable to secure your help, you authorize the Company to act on your behalf (as your agent and attorney-in-fact) in securing all rights related to All IP.
8. **Confidentiality.** As an contributor or contractor of the Company, you will have access to sensitive confidential information that is important to the Company's business. You are responsible for keeping this information confidential, including after you end your work for the Company.
"Confidential Information" includes non-public technical details about our products or services, financial information, business strategies and forecasts, customer data, or any other information, data or know-how that is valuable to the Company because it is not publicly known.
The Company's Confidential Information is sensitive and we expect that you'll treat it as such. You agree to only use the Company's Confidential Information for the purpose of performing your job and for the benefit of the Company. You will do your best to keep Confidential Information secret. If you are not sure if something is Confidential Information, you should assume that it is, until you can confirm otherwise.
Print Name: _____________
Sign: ________________
Date: ________________
@@ -0,0 +1,19 @@
FROM mhart/alpine-node:12
# Directory where the service will be installed
ARG API_DIR=/usr/src/master-app-api
# Prepare required directories
RUN mkdir -p ${API_DIR}
# Use app directory as current workdir
WORKDIR ${API_DIR}
# Copy package.json to workdir
COPY . ${API_DIR}/
# Install dependencies
RUN npm install --production
# Expose Port
EXPOSE $PORT
@@ -0,0 +1,21 @@
FROM mhart/alpine-node:8
ENV PORT=4100
RUN mkdir -p /var/www/app && \
mkdir -p /var/www/app/node_modules
# Use app directory as current workdir
WORKDIR /var/www/app
ENV PATH /var/www/app/node_modules/.bin:$PATH
# Copy package.json to workdir
COPY package.json /var/www/app/package.json
# Install dependencies
RUN npm install
# Copy application code
COPY . /var/www/app
# Expose Port
EXPOSE $PORT
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,24 @@
version: '3'
services:
node:
image: masterappapi-dev:v1
build:
context: .
dockerfile: ./Dockerfile.prod
env_file: ./.env
container_name: masterappapi
tty: true
stdin_open: true
volumes:
- ./:/var/www/app
- /var/www/app/node_modules
working_dir: /var/www/app
restart: always
command: node .
expose:
- 4100
network_mode: webproxy
networks:
default:
external:
name: webproxy
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,41 @@
{
"name": "@superalgos/master-app-api",
"version": "0.1.0",
"description": "Responsible for loading all web modules and running them.",
"author": "Superalgos, ltd.",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/Superalgos/MasterApp.git"
},
"bugs": {
"url": "https://github.com/Superalgos/MasterApp/issues"
},
"homepage": "https://github.com/Superalgos/MasterApp#readme",
"main": "src/index.js",
"scripts": {
"start": "nodemon src/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"devDependencies": {
"nodemon": "1.19.1"
},
"dependencies": {
"apollo-link": "1.2.12",
"apollo-link-context": "1.0.18",
"apollo-link-http": "1.5.5",
"apollo-server-express": "2.6.4",
"axios": "0.19.0",
"body-parser": "1.19.0",
"dotenv": "8.0.0",
"esm": "3.2.25",
"express": "4.17.1",
"express-jwt": "5.3.1",
"graphql": "14.3.1",
"graphql-tools": "4.0.5",
"jwks-rsa": "1.5.1",
"lodash.merge": "4.6.1",
"node-fetch": "2.6.0",
"winston": "3.2.1"
}
}
+220
View File
@@ -0,0 +1,220 @@
import express from 'express'
import 'dotenv/config'
import { ApolloServer, ForbiddenError } from 'apollo-server-express'
import { mergeSchemas } from 'graphql-tools'
import jwt from 'express-jwt'
import jwksRsa from 'jwks-rsa'
import axios from 'axios'
import { createTransformedRemoteSchema } from './createRemoteSchema'
import { teams, events, operations } from './links'
import logger from './logger'
import bodyParser from 'body-parser'
async function getUserId (authId) {
try {
const userData = await axios({
url: process.env.USERS_API_URL,
method: 'post',
headers: {
preshared: process.env.USERS_API_PRESHARED
},
data: {
query: `
{
userByAuthId(authId: "${authId}")
{
id
}
}
`
}
})
return userData.data.data.userByAuthId.id
} catch (error) {
return (error)
}
}
async function run () {
const transformedKeyVaultSchema = await createTransformedRemoteSchema(
'keyVault_',
process.env.KEYVAULT_API_URL,
process.env.KEYVAULT_API_PRESHARED)
const transformedTeamsSchema = await createTransformedRemoteSchema(
'teams_',
process.env.TEAMS_API_URL,
process.env.TEAMS_API_PRESHARED)
const transformedUsersSchema = await createTransformedRemoteSchema(
'users_',
process.env.USERS_API_URL,
process.env.USERS_API_PRESHARED)
const transformedEventsSchema = await createTransformedRemoteSchema(
'events_',
process.env.EVENTS_API_URL,
process.env.EVENTS_API_PRESHARED)
const transformedOperationsSchema = await createTransformedRemoteSchema(
'operations_',
process.env.OPERATIONS_API_URL,
process.env.OPERATIONS_API_PRESHARED)
const transformedNotificationsSchema = await createTransformedRemoteSchema(
'notifications_',
process.env.NOTIFICATIONS_API_URL,
process.env.NOTIFICATIONS_API_PRESHARED)
const transformedLogsSchema = await createTransformedRemoteSchema(
'logs_',
process.env.LOGS_API_URL,
process.env.LOGS_API_PRESHARED)
const transformedStrategizerSchema = await createTransformedRemoteSchema(
'strategizer_',
process.env.STRATEGIZER_API_URL,
process.env.STRATEGIZER_API_PRESHARED)
const transformedCockpitSchema = await createTransformedRemoteSchema(
'cockpit_',
process.env.COCKPIT_API_URL,
process.env.COCKPIT_API_PRESHARED)
const transformedSAWeb = await createTransformedRemoteSchema(
'web_',
process.env.SAWEB_API_URL,
process.env.SAWEB_API_PRESHARED)
var schemas = []
var resolvers = {}
if (transformedTeamsSchema) {
schemas.push(transformedTeamsSchema)
if (transformedUsersSchema && transformedEventsSchema && transformedStrategizerSchema) {
schemas.push(teams.linkSchemaDefs)
resolvers = Object.assign(resolvers, teams.resolver(transformedUsersSchema, transformedEventsSchema, transformedStrategizerSchema))
}
}
if (transformedUsersSchema) {
schemas.push(transformedUsersSchema)
}
if (transformedEventsSchema) {
schemas.push(transformedEventsSchema)
if (transformedUsersSchema && transformedTeamsSchema && transformedOperationsSchema) {
schemas.push(events.linkSchemaDefs)
resolvers = Object.assign(resolvers, events.resolver(transformedUsersSchema, transformedTeamsSchema, transformedOperationsSchema))
}
}
if (transformedKeyVaultSchema) {
schemas.push(transformedKeyVaultSchema)
}
if (transformedOperationsSchema) {
schemas.push(transformedOperationsSchema)
if (transformedTeamsSchema && transformedCockpitSchema) {
schemas.push(operations.linkSchemaDefs)
resolvers = Object.assign(resolvers, operations.resolver(transformedTeamsSchema, transformedCockpitSchema))
}
}
if (transformedNotificationsSchema) {
schemas.push(transformedNotificationsSchema)
}
if (transformedLogsSchema) {
schemas.push(transformedLogsSchema)
}
if (transformedStrategizerSchema) {
schemas.push(transformedStrategizerSchema)
}
if (transformedCockpitSchema) {
schemas.push(transformedCockpitSchema)
}
if (transformedSAWeb) {
schemas.push(transformedSAWeb)
}
const schema = mergeSchemas({
schemas,
resolvers
})
const app = express()
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use('/graphql',
jwt({
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 1,
jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`
}),
credentialsRequired: false,
audience: process.env.AUTH0_AUDIENCE,
issuer: process.env.AUTH0_ISSUER,
algorithms: [`RS256`]
}),
function (err, req, res, next) {
if (err.code === 'invalid_token') {
res.locals.error = err.message
}
return next()
}
)
app.use('/graphql', (req, res, next) => {
res.locals.userId = ''
if (req.user) {
getUserId(req.user.sub)
.then(data => {
res.locals.userId = data
next()
})
.catch(err => {
console.log(err)
next()
})
} else {
next()
}
})
const context = ({ req, res }) => {
if (res.locals.error) {
throw new ForbiddenError(res.locals.error)
}
const response = {
headers: Object.assign(
res.locals.userId ? { userId: res.locals.userId } : {},
req.headers.authorization ? { authorization: req.headers.authorization } : {},
req.headers.keyvault ? { keyvault: req.headers.keyvault } : {}
)
}
return response
}
const server = new ApolloServer({
schema,
context,
formatError: error => {
logger.error('An error ocurred inside a module: %s', error.message)
return error.message
},
formatResponse: response => {
logger.debug('Response from Apollo Server: ' + response)
return response
},
playground: {
settings: {
'editor.theme': 'dark',
'editor.cursorShape': 'line'
}
}
})
server.applyMiddleware({ app, cors: { origin: true, credentials: true, methods:'GET,PUT,POST,DELETE,OPTIONS'}})
app.listen(4100)
logger.info(`Server running. Open ${process.env.GRAPHQL_API_URL} to run queries.`)
}
try {
run()
} catch (e) {
logger.error(`An general error occured while running the app: ${e}, details: ${e.message}, stack: ${e.stack}`)
}
@@ -0,0 +1,62 @@
import fetch from 'node-fetch'
import { createHttpLink } from 'apollo-link-http'
import { setContext } from 'apollo-link-context'
import { ApolloLink } from 'apollo-link'
import {
makeRemoteExecutableSchema,
introspectSchema,
transformSchema,
RenameTypes,
RenameRootFields
} from 'graphql-tools'
import { capitalize } from './utils'
import logger from './logger'
export const createRemoteSchema = async (uri, preshared_key) => {
const makeDatabaseServiceLink = () => createHttpLink({
uri: uri,
headers: {
preshared: preshared_key
},
fetch
})
const databaseServiceSchemaDefinition = await introspectSchema(makeDatabaseServiceLink())
const http = makeDatabaseServiceLink()
const authLink = setContext((request, previousContext) => {
return (
{
headers: {
Authorization: previousContext.graphqlContext.headers.authorization ? previousContext.graphqlContext.headers.authorization : '',
UserId: previousContext.graphqlContext.headers.userId ? previousContext.graphqlContext.headers.userId : '',
keyvault: previousContext.graphqlContext.headers.keyvault ? previousContext.graphqlContext.headers.keyvault : ''
}
}
)
})
return makeRemoteExecutableSchema({
schema: databaseServiceSchemaDefinition,
link: ApolloLink.from([authLink, http])
})
}
export const createTransformedRemoteSchema = async (prefix, uri, preshared_key) => {
var schema
try {
logger.info('About to create %s schema at %s.', prefix, uri)
schema = await createRemoteSchema(uri, preshared_key)
} catch (error) {
logger.error('An error occured while fetching %s, %s schema. Details: %j', prefix, uri, error)
return false
}
const transformedSchema = transformSchema(schema, [
new RenameTypes((name) => prefix + capitalize(name)),
new RenameRootFields((operation, name) => prefix + capitalize(name))
])
return transformedSchema
}
export default createRemoteSchema
@@ -0,0 +1,2 @@
require = require('esm')(module)
module.exports = require('./app.js')
@@ -0,0 +1,164 @@
export const linkSchemaDefs =
`
extend type events_Event {
host: users_User
}
extend type events_Event {
participatingAs: [teams_Team]
}
extend type events_Event {
canParticipateAs: [teams_Team]
}
extend type events_Inviter {
inviter: users_User
}
extend type events_Formula {
owner: users_User
}
extend type events_Plotter {
owner: users_User
}
extend type events_Participant {
participant: teams_Team
}
extend type events_Participant {
clone: operations_GetClones
}
extend type events_Invitation {
invitee: teams_Team
}
`
export const resolver = (usersSchema, teamsSchema, operationsSchema) => ({
events_Event: {
host: {
fragment: `fragment UserFragment on events_Event{hostId}`,
resolve ({hostId : id}, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: usersSchema,
operation: 'query',
fieldName: 'users_User',
args: { id },
context,
info
})
}
},
participatingAs: {
fragment: `fragment TeamFragment on events_Event{participatingAsId}`,
resolve ({participatingAsId : teamIds}, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: teamsSchema,
operation: 'query',
fieldName: 'teams_TeamsByIds',
args: { teamIds },
context,
info
})
}
},
canParticipateAs: {
fragment: `fragment TeamFragment on events_Event{canParticipateAsId}`,
resolve ({canParticipateAsId : teamIds}, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: teamsSchema,
operation: 'query',
fieldName: 'teams_TeamsByIds',
args: { teamIds },
context,
info
})
}
}
},
events_Inviter: {
inviter: {
fragment: `fragment UserFragment on events_Inviter{inviterId}`,
resolve ({inviter : id}, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: usersSchema,
operation: 'query',
fieldName: 'users_User',
args: { id },
context,
info
})
}
}
},
events_Formula: {
owner: {
fragment: `fragment UserFragment on events_Formula{ownerId}`,
resolve ({owner : id}, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: usersSchema,
operation: 'query',
fieldName: 'users_User',
args: { id },
context,
info
})
}
}
},
events_Plotter: {
owner: {
fragment: `fragment UserFragment on events_Plotter{ownerId}`,
resolve ({owner : id}, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: usersSchema,
operation: 'query',
fieldName: 'users_User',
args: { id },
context,
info
})
}
}
},
events_Participant: {
participant: {
fragment: `fragment TeamFragment on events_Participant{participantId}`,
resolve ({participantId : teamId}, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: teamsSchema,
operation: 'query',
fieldName: 'teams_TeamById',
args: { teamId },
context,
info
})
}
},
clone: {
fragment: `fragment CloneFragment on events_Participant{operationId}`,
resolve ({operationId: cloneId}, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: operationsSchema,
operation: 'query',
fieldName: 'operations_GetClone',
args: { cloneId },
context,
info
})
}
}
},
events_Invitation: {
invitee: {
fragment: `fragment TeamFragment on events_Invitation{inviteeId}`,
resolve ({inviteeId : teamId}, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: teamsSchema,
operation: 'query',
fieldName: 'teams_TeamById',
args: { teamId },
context,
info
})
}
}
},
})
export default { resolver, linkSchemaDefs }
@@ -0,0 +1,5 @@
import teams from './teams'
import events from './events'
import operations from './operations'
export { teams, events, operations }
@@ -0,0 +1,60 @@
export const linkSchemaDefs =
`
extend type operations_GetClones {
team: teams_Team
}
extend type operations_GetClones {
bot: teams_FinancialBeings
}
extend type operations_Clone {
signals( orderStatus: String ): [cockpit_Signal]
}
`
export const resolver = (teamsSchema, cockpitSchema) => ({
operations_Clone: {
signals: {
fragment: `fragment SignalFragment on operations_Clone{id}`,
resolve ({id: cloneId}, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: cockpitSchema,
operation: 'query',
fieldName: 'cockpit_SignalsByCloneId',
args: { ...args, cloneId },
context,
info
})
}
}
},
operations_GetClones: {
team: {
fragment: `fragment TeamFragment on operations_GetClones{teamId}`,
resolve ({teamId}, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: teamsSchema,
operation: 'query',
fieldName: 'teams_TeamById',
args: { teamId },
context,
info
})
}
},
bot: {
fragment: `fragment TeamFragment on operations_GetClones{botId}`,
resolve ({botId: fbId}, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: teamsSchema,
operation: 'query',
fieldName: 'teams_FbByFbId',
args: { fbId },
context,
info
})
}
}
}
})
export default { resolver, linkSchemaDefs }
@@ -0,0 +1,67 @@
export const linkSchemaDefs =
`
extend type teams_Team {
ownerUser: users_User
}
extend type teams_Team {
events(
hostId: String,
inviteeId: String,
minStartDate: Int,
maxStartDate: Int,
minEndDate: Int,
maxEndDate: Int
): [events_Event]
}
extend type teams_FinancialBeings {
tradingSystem: strategizer_TradingSystem
}
`
export const resolver = (usersSchema, eventsSchema, strategizerSchema) => ({
teams_FinancialBeings: {
tradingSystem: {
fragment: `fragment TradingSystemFragment on teams_FinancialBeings{slug}`,
resolve ({slug: fbSlug}, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: strategizerSchema,
operation: 'query',
fieldName: 'strategizer_TradingSystemByFb',
args: { fbSlug },
context,
info
})
}
}
},
teams_Team: {
ownerUser: {
fragment: `fragment UserFragment on teams_Team{owner}`,
resolve ({owner: id}, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: usersSchema,
operation: 'query',
fieldName: 'users_User',
args: { id },
context,
info
})
}
},
events: {
fragment: `fragment EventFragment on teams_Team{id}`,
resolve ({id: participantId}, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: eventsSchema,
operation: 'query',
fieldName: 'events_Events',
args: { ...args, participantId },
context,
info
})
}
}
}
})
export default { resolver, linkSchemaDefs }
@@ -0,0 +1,42 @@
import { createLogger, format, transports } from 'winston'
import { inspect } from 'util'
const { combine, timestamp, simple } = format
const options = {
file: {
level: 'info',
filename: '../logs/app.log',
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
timestamp: true
},
console: {
level: 'info',
handleExceptions: true,
json: false,
colorize: true,
}
}
const logger = createLogger({
level: 'info',
format: format.combine(
format.colorize(),
format.splat(),
format.timestamp({ format: 'YY/MM/DD HH:mm' }),
format.printf(
info => `${info.timestamp} - ${info.level}: ${JSON.parse(JSON.stringify(inspect(info.message)))}`
)
),
transports: [
new transports.File(options.file),
new transports.Console(options.console)
],
exitOnError: false // do not exit on handled exceptions
})
export default logger
@@ -0,0 +1,10 @@
import merge from 'lodash.merge'
// import { SendgridMutations } from './mutation'
const resolvers = {
Mutation: {
// ...SendgridMutations
}
}
export default resolvers
Whitespace-only changes.
@@ -0,0 +1,9 @@
export const typeDef = `
type Mutation {
master_SampleMutation(variable: String!): String
}
schema {
mutation: Mutation
}
`
@@ -0,0 +1,20 @@
import fs from 'fs'
import path from 'path'
export const mergeDirectoryModules = dirpath =>
fs
.readdirSync(dirpath, 'utf8')
.filter(filename => !/^[_|index.]/.test(filename))
.reduce(
(acc, filename) => ({
...acc,
...require(path.resolve(dirpath, filename)).default,
}),
{}
)
export const capitalize = (string) => {
return (string).charAt(0).toUpperCase() + (string).slice(1)
}
export default capitalize
+79
View File
@@ -0,0 +1,79 @@
#!/bin/sh
TIMEOUT=15
QUIET=0
echoerr() {
if [ "$QUIET" -ne 1 ]; then printf "%s\n" "$*" 1>&2; fi
}
usage() {
exitcode="$1"
cat << USAGE >&2
Usage:
$cmdname host:port [-t timeout] [-- command args]
-q | --quiet Do not output any status messages
-t TIMEOUT | --timeout=timeout Timeout in seconds, zero for no timeout
-- COMMAND ARGS Execute command with args after the test finishes
USAGE
exit "$exitcode"
}
wait_for() {
for i in `seq $TIMEOUT` ; do
nc -z "$HOST" "$PORT" > /dev/null 2>&1
result=$?
if [ $result -eq 0 ] ; then
if [ $# -gt 0 ] ; then
exec "$@"
fi
exit 0
fi
sleep 1
done
echo "Operation timed out" >&2
exit 1
}
while [ $# -gt 0 ]
do
case "$1" in
*:* )
HOST=$(printf "%s\n" "$1"| cut -d : -f 1)
PORT=$(printf "%s\n" "$1"| cut -d : -f 2)
shift 1
;;
-q | --quiet)
QUIET=1
shift 1
;;
-t)
TIMEOUT="$2"
if [ "$TIMEOUT" = "" ]; then break; fi
shift 2
;;
--timeout=*)
TIMEOUT="${1#*=}"
shift 1
;;
--)
shift
break
;;
--help)
usage 0
;;
*)
echoerr "Unknown argument: $1"
usage 1
;;
esac
done
if [ "$HOST" = "" -o "$PORT" = "" ]; then
echoerr "Error: you need to provide a host and port to test."
usage 2
fi
wait_for "$@"