Separating front and back

This commit is contained in:
Unknown committed 2019-02-10 18:00:29 +01:00
1 parent 14484b493e
commit 64ce8699cb
64 files changed
+9705 -1

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
import 'dotenv/config';
import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import * as Sentry from '@sentry/node';
import schema from './schema';
import wrongPreshared from './errors/notAllowed.json';
const app = express();
// Initialising sentry
Sentry.init({ dsn: process.env.SENTRY_DNS });
app.use(Sentry.Handlers.requestHandler());
app.post('/graphql', (req, res, next) => {
if (req.headers.preshared === process.env.PRESHARED_GATEWAY_KEY) {
next();
} else {
res.send(wrongPreshared);
}
});
// Starting the graphql server
const server = new ApolloServer({
schema,
playground: {
settings: {
'editor.theme': 'dark',
'editor.cursorShape': 'line',
},
},
context: ({ req }) => ({
userId: req.headers.userid,
authorization: req.headers.authorization,
}),
formatError: error => ({
code: error.extensions.exception.code,
message: error.message,
path: error.path,
}),
introspection: true,
});
server.applyMiddleware({
app,
cors: true,
});
// Sentry error handling middleware if anything pass through
app.use(Sentry.Handlers.errorHandler());
export default app;
+11
View File
@@ -0,0 +1,11 @@
import 'dotenv/config';
import mongoose from 'mongoose';
mongoose.connect(`mongodb://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@${process.env.DB_DOMAIN}`, { useNewUrlParser: true });
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);
mongoose.Promise = global.Promise;
const db = mongoose.connection;
export default db;
+21
View File
@@ -0,0 +1,21 @@
export const UNPUBLISHED = 'UNPUBLISHED';
export const PUBLISHED = 'PUBLISHED';
export const CANCELLED = 'CANCELLED';
export const STARTING = 'STARTING';
export const RUNNING = 'RUNNING';
export const INTERRUPTED = 'INTERRUPTED';
export const FINISHED = 'FINISHED';
export const ARCHIVED = 'ARCHIVED';
export const EventStateEnum = [
UNPUBLISHED,
PUBLISHED,
CANCELLED,
STARTING,
RUNNING,
INTERRUPTED,
FINISHED,
ARCHIVED,
];
export default EventStateEnum;
+11
View File
@@ -0,0 +1,11 @@
export const STATECHANGE = 'STATECHANGE';
export const DATACHANGE = 'DATACHANGE';
export const OTHER = 'OTHER';
export const HistoryTypeEnum = [
STATECHANGE,
DATACHANGE,
OTHER,
];
export default HistoryTypeEnum;
+11
View File
@@ -0,0 +1,11 @@
export const ENLISTED = 'ENLISTED';
export const DELISTED = 'DELISTED';
export const DISQUALIFIED = 'DISQUALIFIED';
export const ParticipantStateEnum = [
ENLISTED,
DELISTED,
DISQUALIFIED,
];
export default ParticipantStateEnum;
+51
View File
@@ -0,0 +1,51 @@
import * as Sentry from '@sentry/node';
class ClientError extends Error {
constructor(args) {
super(args);
Sentry.configureScope((scope) => {
scope.setLevel('debug');
});
Sentry.captureException(this);
}
}
class ServerError extends Error {
constructor(args) {
super(args);
Sentry.configureScope((scope) => {
scope.setLevel('error');
});
Sentry.captureException(this);
}
}
export class AuthentificationError extends ClientError {
code = 401
message = 'Autentification not found, you have to be authentificated to perform this action'
}
export class DatabaseError extends ClientError {
code = 404
message = `Ressource not found : ${this.message}`
}
export class WrongArgumentsError extends ClientError {
code = 400
message = `Wrong arguments : ${this.message}`
}
export class NotImplementedYetError extends ServerError {
code = 501
message = `This is not implemented yet, but will be soon. ${this.message}`
}
export class ServiceUnavailableError extends ServerError {
code = 503
message = `At least one service is unresponding ${this.message}`
}
+8
View File
@@ -0,0 +1,8 @@
{
"errors": [
{
"code": 401,
"message": "Wait, you're not supposed to be here, go through the gate as everyone else"
}
]
}
+22
View File
@@ -0,0 +1,22 @@
/* eslint-disable no-console */
import * as Sentry from '@sentry/node';
import db from './db';
import app from './app';
// Bind server success and error to sentry
db.on('error', (err) => {
Sentry.configureScope((scope) => {
scope.setLevel('error');
});
Sentry.captureException(err);
});
db.once('open', () => {
Sentry.configureScope((scope) => {
scope.setLevel('info');
});
Sentry.captureMessage('Connected to the DB.');
});
app.listen(process.env.PORT, () => {
console.log(`Listening on port ${process.env.PORT}`);
});
+191
View File
@@ -0,0 +1,191 @@
import mongoose, { Schema } from 'mongoose';
import Plotter from './plotter';
import Formula from './formula';
import {
UNPUBLISHED,
EventStateEnum,
} from '../enums/EventState';
import {
ENLISTED,
ParticipantStateEnum,
} from '../enums/ParticipantState';
import {
OTHER,
HistoryTypeEnum,
} from '../enums/HistoryType';
const { ObjectId } = Schema.Types;
const eventSchema = new Schema({
title: {
type: String,
required: true,
},
subtitle: {
type: String,
required: true,
},
hostId: {
type: String,
required: true,
},
description: String,
startDatetime: {
type: Number,
required: true,
},
finishDatetime: {
type: Number,
required: true,
},
state: {
type: String,
enum: EventStateEnum,
default: UNPUBLISHED,
},
history: [{
date: {
type: Number,
required: true,
},
action: {
data: String,
type: {
type: String,
enum: HistoryTypeEnum,
default: OTHER,
},
comment: String,
},
}],
rules: [{
title: {
type: String,
required: true,
},
description: String,
}],
rulesHistory: [{
date: {
type: Number,
required: true,
},
action: {
data: String,
type: {
type: String,
enum: HistoryTypeEnum,
default: OTHER,
},
comment: String,
},
}],
prizes: [{
condition: {
from: Number,
to: Number,
additional: String,
},
pool: {
amount: {
type: Number,
required: true,
},
asset: {
type: String,
required: true,
},
},
}],
prizesHistory: [{
date: {
type: Number,
required: true,
},
action: {
data: String,
type: {
type: String,
enum: HistoryTypeEnum,
default: OTHER,
},
comment: String,
},
}],
participants: [{
participantId: {
type: String,
required: true,
},
state: {
type: String,
enum: ParticipantStateEnum,
default: ENLISTED,
},
history: [{
date: {
type: Number,
required: true,
},
action: {
data: String,
type: {
type: String,
enum: HistoryTypeEnum,
default: OTHER,
},
comment: String,
},
}],
operationId: String,
}],
invitations: [{
inviteeId: {
type: String,
required: true,
},
acceptedDate: Number,
refusedDate: Number,
by: {
date: Number,
inviterId: {
type: String,
required: true,
},
},
}],
presentation: {
banner: String,
profile: String,
page: String,
},
formulaId: {
type: ObjectId,
ref: Formula.modelName,
},
plotterId: {
type: ObjectId,
ref: Plotter.modelName,
},
});
eventSchema.pre('find', function populate() {
this.populate('formulaId').populate('plotterId');
});
eventSchema.pre('findOne', function populate() {
this.populate('formulaId').populate('plotterId');
});
eventSchema.post('save', (doc, next) => {
doc.populate('formulaId').populate('plotterId').execPopulate().then(() => {
next();
});
});
eventSchema.post('findOneAndUpdate', (doc, next) => {
doc.populate('formulaId').populate('plotterId').execPopulate().then(() => {
next();
});
});
const Event = mongoose.model('Event', eventSchema);
export default Event;
+20
View File
@@ -0,0 +1,20 @@
import mongoose, { Schema } from 'mongoose';
const formulaSchema = new Schema({
ownerId: {
type: String,
required: true,
},
isTemplate: {
type: Boolean,
default: false,
},
name: {
type: String,
required: true,
},
});
const Formula = mongoose.model('Formula', formulaSchema);
export default Formula;
+9
View File
@@ -0,0 +1,9 @@
import Plotter from './plotter';
import Event from './event';
import Formula from './formula';
export {
Event,
Plotter,
Formula,
};
+32
View File
@@ -0,0 +1,32 @@
import mongoose, { Schema } from 'mongoose';
const plotterSchema = new Schema({
ownerId: {
type: String,
required: true,
},
isTemplate: {
type: Boolean,
default: false,
},
name: {
type: String,
required: true,
},
host: {
type: String,
required: true,
},
repo: {
type: String,
required: true,
},
moduleName: {
type: String,
required: true,
},
});
const Plotter = mongoose.model('Plotter', plotterSchema);
export default Plotter;
+13
View File
@@ -0,0 +1,13 @@
import {
GraphQLSchema,
} from 'graphql';
import Mutation from './mutations';
import RootQuery from './queries';
const Schema = new GraphQLSchema({
query: RootQuery,
mutation: Mutation,
});
export default Schema;
+81
View File
@@ -0,0 +1,81 @@
import {
GraphQLNonNull,
GraphQLID,
} from 'graphql';
import {
WrongArgumentsError,
AuthentificationError,
NotImplementedYetError,
} from '../../errors';
import { EventType } from '../types';
import { Event } from '../../models';
import EventStateEnum from '../types/enum/EventState';
import {
UNPUBLISHED,
PUBLISHED,
CANCELLED,
STARTING,
RUNNING,
INTERRUPTED,
FINISHED,
ARCHIVED,
} from '../../enums/EventState';
const args = {
eventId: { type: new GraphQLNonNull(GraphQLID) },
state: { type: EventStateEnum },
};
const resolve = (parent, { eventId: _id, state }, { userId: hostId }) => {
if (!hostId) {
throw new AuthentificationError();
}
switch (state) {
case PUBLISHED:
return new Promise((res, rej) => {
Event.findOneAndUpdate({ _id, hostId, state: UNPUBLISHED }, { state }, { new: true }, (err, modifiedEvent) => {
if (err) {
rej(err);
return;
}
res(modifiedEvent);
});
});
case CANCELLED:
throw new NotImplementedYetError('We are still wondering about cancellation conditions, '
+ 'if you have any inputs or proposition don\t hesitate to contact us');
case STARTING:
throw new NotImplementedYetError('Still working on it');
case RUNNING:
throw new NotImplementedYetError('Still working on it');
case INTERRUPTED:
throw new NotImplementedYetError('We are still wondering about interuption conditions, '
+ 'if you have any inputs or proposition don\t hesitate to contact us');
case FINISHED:
throw new NotImplementedYetError('Still working on it');
case ARCHIVED:
return new Promise((res, rej) => {
Event.findOneAndUpdate({ _id, hostId, state: FINISHED }, { state }, { new: true }, (err, modifiedEvent) => {
if (err) {
rej(err);
return;
}
res(modifiedEvent);
});
});
default:
throw new WrongArgumentsError('You shouldn\'t even be allowed to be there');
}
};
const mutation = {
changeEventState: {
type: EventType,
args,
resolve,
},
};
export default mutation;
+37
View File
@@ -0,0 +1,37 @@
import { AuthentificationError } from '../../errors';
import { EventType } from '../types';
import { Event } from '../../models';
import { EventInputType } from '../types/input';
export const args = {
event: { type: EventInputType },
};
const resolve = (parent, { event }, { userId: hostId }) => {
if (!hostId) {
throw new AuthentificationError();
}
event.hostId = hostId;
const newEvent = new Event(event);
return new Promise((res, rej) => {
newEvent.save((err) => {
if (err) {
rej(err);
return;
}
res(newEvent);
});
});
};
const mutation = {
createEvent: {
type: EventType,
args,
resolve,
},
};
export default mutation;
+37
View File
@@ -0,0 +1,37 @@
import { AuthentificationError } from '../../errors';
import { FormulaType } from '../types';
import { Formula } from '../../models';
import { FormulaInputType } from '../types/input';
const args = {
formula: { type: FormulaInputType },
};
const resolve = (parent, { formula }, { userId: ownerId }) => {
if (!ownerId) {
throw new AuthentificationError();
}
formula.ownerId = ownerId;
const newFormula = new Formula(formula);
return new Promise((res, rej) => {
newFormula.save((err) => {
if (err) {
rej(err);
return;
}
res(newFormula);
});
});
};
const mutation = {
createFormula: {
type: FormulaType,
args,
resolve,
},
};
export default mutation;
+37
View File
@@ -0,0 +1,37 @@
import { AuthentificationError } from '../../errors';
import { PlotterType } from '../types';
import { Plotter } from '../../models';
import { PlotterInputType } from '../types/input';
const args = {
plotter: { type: PlotterInputType },
};
const resolve = (parent, { plotter }, { userId: ownerId }) => {
if (!ownerId) {
throw new AuthentificationError();
}
plotter.ownerId = ownerId;
const newPlotter = new Plotter(plotter);
return new Promise((res, reject) => {
newPlotter.save((err) => {
if (err) {
reject(err);
return;
}
res(newPlotter);
});
});
};
const mutation = {
createPlotter: {
type: PlotterType,
args,
resolve,
},
};
export default mutation;
+39
View File
@@ -0,0 +1,39 @@
import {
GraphQLNonNull,
GraphQLID,
} from 'graphql';
import { AuthentificationError } from '../../errors';
import { EventType } from '../types';
import { Event } from '../../models';
import { EventInputType } from '../types/input';
const args = {
eventId: { type: new GraphQLNonNull(GraphQLID) },
event: { type: EventInputType },
};
const resolve = (parent, { eventId: _id, event }, { userId: hostId }) => {
if (!hostId) {
throw new AuthentificationError();
}
return new Promise((res, rej) => {
Event.findOneAndUpdate({ _id, hostId }, event, { new: true }, (err, modifiedEvent) => {
if (err) {
rej(err);
return;
}
res(modifiedEvent);
});
});
};
const mutation = {
editEvent: {
type: EventType,
args,
resolve,
},
};
export default mutation;
+127
View File
@@ -0,0 +1,127 @@
import {
GraphQLNonNull,
GraphQLID,
} from 'graphql';
import axios from 'axios';
import {
AuthentificationError,
WrongArgumentsError,
ServiceUnavailableError,
} from '../../errors';
import { EventType } from '../types';
import { Event } from '../../models';
import { ParticipantInputType } from '../types/input';
const args = {
eventId: { type: new GraphQLNonNull(GraphQLID) },
participant: { type: ParticipantInputType },
};
const resolve = (parent,
{ eventId: _id, participant: { participantId, botId } },
{ userId, authorization }) => {
if (!userId) {
throw new AuthentificationError();
}
return new Promise((res, rej) => {
axios({
url: process.env.GATEWAY_ENDPOINT,
method: 'post',
data: {
query: `
{
teams_TeamsByRole{
id
}
}
`,
},
headers: { authorization },
}).then(
(result) => {
if (!result.data.data.teams_TeamsByRole.some(team => team.id === participantId)) {
rej(new WrongArgumentsError('You are not eligible to edit this team'));
return;
}
Event.findOne({ _id }).exec((err, event) => {
if (err) {
rej(err);
return;
}
const participantIndex = event.participant
.findIndex(participant => participant.participantId === participantId);
axios({
url: process.env.GATEWAY_ENDPOINT,
method: 'post',
data: {
query: `
mutation {
operations_RemoveClone(id: "${event.participants[participantIndex].operationId}")
}
`,
},
headers: { authorization },
}).then(
() => {
axios({
url: process.env.GATEWAY_ENDPOINT,
method: 'post',
data: {
query: `
mutation {
operations_AddClone(
clone: {
botId: "${botId}"
botType: "Trading"
mode: "competition"
resumeExecution: false
runAsTeam: true
teamId: "${participantId}"
processName: "${event.title}-${participantId}"
}
) {
id
}
}
`,
},
headers: { authorization },
}).then(
(operationCreation) => {
event.participants[participantIndex].operationId = operationCreation.data.data.operations_AddClone.id;
event.save((error) => {
if (error) {
rej(error);
return;
}
res(event);
});
},
(error) => {
rej(new ServiceUnavailableError(error));
},
);
},
(error) => {
rej(new ServiceUnavailableError(error));
},
);
});
},
(error) => {
rej(new ServiceUnavailableError(error));
},
);
});
};
const mutation = {
editParticipant: {
type: EventType,
args,
resolve,
},
};
export default mutation;
+62
View File
@@ -0,0 +1,62 @@
import 'dotenv/config';
import {
GraphQLNonNull,
GraphQLID,
GraphQLString,
} from 'graphql';
import {
AuthentificationError,
WrongArgumentsError,
} from '../../errors';
import { epoch } from '../../utils/functions';
import { EventType } from '../types';
import { Event } from '../../models';
const args = {
eventId: { type: new GraphQLNonNull(GraphQLID) },
inviteeId: { type: new GraphQLNonNull(GraphQLString) },
};
const resolve = (parent,
{ eventId: _id, inviteeId },
{ userId }) => {
if (!userId) {
throw new AuthentificationError();
}
return new Promise((res, rej) => {
Event.findOne({ _id }).exec((err, event) => {
if (err) {
rej(err);
return;
}
if (event.invitations.some(invitee => invitee.inviteeId === inviteeId)) {
rej(new WrongArgumentsError('This user is already invited'));
return;
}
event.invitations.push({
inviteeId,
by: {
inviterId: userId,
date: epoch(),
},
});
event.save((error) => {
if (error) {
rej(error);
return;
}
res(event);
});
});
});
};
const mutation = {
inviteAtEvent: {
type: EventType,
args,
resolve,
},
};
export default mutation;
+114
View File
@@ -0,0 +1,114 @@
import 'dotenv/config';
import {
GraphQLNonNull,
GraphQLID,
} from 'graphql';
import axios from 'axios';
import {
AuthentificationError,
WrongArgumentsError,
ServiceUnavailableError,
} from '../../errors';
import { EventType } from '../types';
import { Event } from '../../models';
import { ParticipantInputType } from '../types/input';
const args = {
eventId: { type: new GraphQLNonNull(GraphQLID) },
participant: { type: ParticipantInputType },
};
const resolve = (parent,
{ eventId: _id, participant: { participantId, botId } },
{ userId, authorization }) => {
if (!userId) {
throw new AuthentificationError();
}
return new Promise((res, rej) => {
axios({
url: process.env.GATEWAY_ENDPOINT,
method: 'post',
data: {
query: `
{
teams_TeamsByRole{
id
}
}
`,
},
headers: { authorization },
}).then(
(result) => {
if (!result.data.data.teamsByRole.some(team => team.id === participantId)) {
rej(new WrongArgumentsError('You are not eligible to register this team'));
return;
}
Event.findOne({ _id }).exec((err, event) => {
if (err) {
rej(err);
return;
}
if (event.participants.some(participant => participant.participantId === participantId)) {
rej(new WrongArgumentsError('You are already registred'));
return;
}
axios({
url: process.env.GATEWAY_ENDPOINT,
method: 'post',
data: {
query: `
mutation {
operations_AddClone(
clone: {
botId: "${botId}"
botType: "Trading"
mode: "competition"
resumeExecution: false
runAsTeam: true
teamId: "${participantId}"
processName: "${event.title}-${participantId}"
}
) {
id
}
}
`,
},
headers: { authorization },
}).then(
(operationCreation) => {
event.participants.push({
participantId,
operationId: operationCreation.data.data.operations_AddClone.id,
});
event.save((error) => {
if (error) {
rej(error);
return;
}
res(event);
});
},
(error) => {
rej(new ServiceUnavailableError(error));
},
);
});
},
(error) => {
rej(new ServiceUnavailableError(error));
},
);
});
};
const mutation = {
registerToEvent: {
type: EventType,
args,
resolve,
},
};
export default mutation;
+137
View File
@@ -0,0 +1,137 @@
import 'dotenv/config';
import {
GraphQLNonNull,
GraphQLID,
GraphQLBoolean,
} from 'graphql';
import axios from 'axios';
import {
AuthentificationError,
WrongArgumentsError,
ServiceUnavailableError,
} from '../../errors';
import { epoch } from '../../utils/functions';
import { EventType } from '../types';
import { Event } from '../../models';
import { ParticipantInputType } from '../types/input';
const args = {
eventId: { type: new GraphQLNonNull(GraphQLID) },
answer: { type: new GraphQLNonNull(GraphQLBoolean) },
participant: { type: ParticipantInputType },
};
const resolve = (parent,
{ eventId: _id, answer, participant: { participantId, botId } },
{ userId, authorization }) => {
if (!userId) {
throw new AuthentificationError();
}
return new Promise((res, rej) => {
axios({
url: process.env.GATEWAY_ENDPOINT,
method: 'post',
data: {
query: `
{
teams_TeamsByRole{
id
}
}
`,
},
headers: { authorization },
}).then(
(result) => {
if (!result.data.data.teamsByRole.some(team => team.id === participantId)) {
rej(new WrongArgumentsError('You are not eligible to register this team'));
return;
}
Event.findOne({ _id }).exec((err, event) => {
if (err) {
rej(err);
return;
}
if (event.participants.some(participant => participant.participantId === participantId)) {
rej(new WrongArgumentsError('You are already registred'));
return;
}
if (event.invitations.some(invitee => invitee.inviteeId === userId)) {
const inviteeIndex = event.invitations
.findIndex(invitee => invitee.inviteeId === userId);
if (answer) {
event.invitations[inviteeIndex].acceptedDate = epoch();
axios({
url: process.env.GATEWAY_ENDPOINT,
method: 'post',
data: {
query: `
mutation {
operations_AddClone(
clone: {
botId: "${botId}"
botType: "Trading"
mode: "competition"
resumeExecution: false
runAsTeam: true
teamId: "${participantId}"
processName: "${event.title}-${participantId}"
}
) {
id
}
}
`,
},
headers: { authorization },
}).then(
(operationCreation) => {
event.participants.push({
participantId,
operationId: operationCreation.data.data.operations_AddClone.id,
});
event.save((error) => {
if (error) {
rej(error);
return;
}
res(event);
});
},
(error) => {
rej(new ServiceUnavailableError(error));
},
);
} else {
event.invitations[inviteeIndex].refusedDate = epoch();
}
} else {
rej(new WrongArgumentsError('You were not invited to that event, you might want to simply register if possible'));
}
event.save((error) => {
if (error) {
rej(error);
return;
}
res(event);
});
});
},
(error) => {
rej(new ServiceUnavailableError(error));
},
);
});
};
const mutation = {
respondToInvitation: {
type: EventType,
args,
resolve,
},
};
export default mutation;
+26
View File
@@ -0,0 +1,26 @@
import {
GraphQLObjectType,
} from 'graphql';
import CreateEventMutation from './CreateEvent';
import EditEventMutation from './EditEvent';
import RegisterToEventMutation from './RegisterToEvent';
import EditParticipantMutation from './EditParticipant';
import CreateFormulaMutation from './CreateFormula';
import CreatePlotterMutation from './CreatePlotter';
import ChangeEventStateMutation from './ChangeEventState';
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: Object.assign(
CreateEventMutation,
EditEventMutation,
RegisterToEventMutation,
EditParticipantMutation,
CreateFormulaMutation,
CreatePlotterMutation,
ChangeEventStateMutation,
),
});
export default Mutation;
+35
View File
@@ -0,0 +1,35 @@
import {
GraphQLNonNull,
GraphQLID,
} from 'graphql';
import { DatabaseError } from '../../errors';
import { EventType } from '../types';
import { Event } from '../../models';
const args = {
eventId: { type: new GraphQLNonNull(GraphQLID) },
};
const resolve = (parent, { eventId: _id }) => new Promise((res, rej) => {
Event.findOne({ _id }).exec((err, event) => {
if (err) {
rej(err);
return;
}
if (!event) {
rej(new DatabaseError('None of the events respond to that id'));
return;
}
res(event);
});
});
const query = {
event: {
type: EventType,
args,
resolve,
},
};
export default query;
+79
View File
@@ -0,0 +1,79 @@
import {
GraphQLInt,
GraphQLString,
GraphQLList,
} from 'graphql';
import { AuthentificationError } from '../../errors';
import { EventType } from '../types';
import EventStateEnum from '../types/enum/EventState';
import { Event } from '../../models';
import { UNPUBLISHED, ARCHIVED } from '../../enums/EventState';
const args = {
state: { type: EventStateEnum },
hostId: { type: GraphQLString },
participantId: { type: GraphQLString },
minStartDate: { type: GraphQLInt },
maxStartDate: { type: GraphQLInt },
minEndDate: { type: GraphQLInt },
maxEndDate: { type: GraphQLInt },
};
const resolve = (parent, {
state,
hostId,
participantId,
minStartDate,
maxStartDate,
minEndDate,
maxEndDate,
}, { userId }) => {
if (state === UNPUBLISHED && hostId !== userId) {
throw new AuthentificationError('You cannot get unpublished events of other users.');
}
return new Promise((res, rej) => {
Event.find(
Object.assign(
state ? { state } : { state: { $nin: [UNPUBLISHED, ARCHIVED] } },
hostId ? { hostId } : {},
participantId ? { participants: { $elemMatch: { participantId } } } : {},
minStartDate || maxStartDate
? {
startDatetime:
Object.assign(
minStartDate ? { $gte: minStartDate } : {},
maxStartDate ? { $lte: maxStartDate } : {},
),
}
: {},
minEndDate || maxEndDate
? {
startDatetime:
Object.assign(
minEndDate ? { $gte: minEndDate } : {},
maxEndDate ? { $lte: maxEndDate } : {},
),
}
: {},
), (err, events) => {
if (err) {
rej(err);
return;
}
res(events);
},
);
});
};
const query = {
events: {
type: new GraphQLList(EventType),
args,
resolve,
},
};
export default query;
+19
View File
@@ -0,0 +1,19 @@
import {
GraphQLList,
} from 'graphql';
import { FormulaType } from '../types';
import { Formula } from '../../models';
const args = {};
const resolve = () => Formula.find();
const query = {
formulas: {
type: new GraphQLList(FormulaType),
args,
resolve,
},
};
export default query;
+19
View File
@@ -0,0 +1,19 @@
import {
GraphQLList,
} from 'graphql';
import { PlotterType } from '../types';
import { Plotter } from '../../models';
const args = {};
const resolve = () => Plotter.find();
const query = {
plotters: {
type: new GraphQLList(PlotterType),
args,
resolve,
},
};
export default query;
+20
View File
@@ -0,0 +1,20 @@
import {
GraphQLObjectType,
} from 'graphql';
import EventQuery from './Event';
import EventsQuery from './Events';
import FormulasQuery from './Formulas';
import PlottersQuery from './Plotters';
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: Object.assign(
EventQuery,
EventsQuery,
FormulasQuery,
PlottersQuery,
),
});
export default RootQuery;
+76
View File
@@ -0,0 +1,76 @@
import {
GraphQLObjectType,
GraphQLInt,
GraphQLString,
GraphQLList,
GraphQLID,
} from 'graphql';
import {
FormulaType,
PlotterType,
RuleType,
ParticipantType,
PrizeType,
InvitationType,
PresentationType,
} from './index';
import EventStateEnumType from './enum/EventState';
const EventType = new GraphQLObjectType({
name: 'Event',
description: 'Everything you need to know about an event',
fields: () => ({
id: { type: GraphQLID },
title: { type: GraphQLString },
subtitle: { type: GraphQLString },
hostId: { type: GraphQLString },
description: { type: GraphQLString },
startDatetime: { type: GraphQLInt },
finishDatetime: { type: GraphQLInt },
state: { type: EventStateEnumType },
rules: {
type: new GraphQLList(RuleType),
resolve(parent) {
return parent.rules;
},
},
prizes: {
type: new GraphQLList(PrizeType),
resolve(parent) {
return parent.prizes;
},
},
participants: {
type: new GraphQLList(ParticipantType),
resolve(parent) {
return parent.participants;
},
},
invitations: {
type: new GraphQLList(InvitationType),
resolve(parent) {
return parent.invitations;
},
},
presentation: {
type: PresentationType,
resolve(parent) {
return parent.presentation;
},
},
formula: {
type: FormulaType,
resolve(parent) {
return parent.formulaId;
},
},
plotter: {
type: PlotterType,
resolve(parent) {
return parent.plotterId;
},
},
}),
});
export default EventType;
+19
View File
@@ -0,0 +1,19 @@
import {
GraphQLObjectType,
GraphQLID,
GraphQLString,
GraphQLBoolean,
} from 'graphql';
const FormulaType = new GraphQLObjectType({
name: 'Formula',
description: 'For now it\'s simply a named field',
fields: () => ({
id: { type: GraphQLID },
ownerId: { type: GraphQLString },
isTemplate: { type: GraphQLBoolean },
name: { type: GraphQLString },
}),
});
export default FormulaType;
+21
View File
@@ -0,0 +1,21 @@
import {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
} from 'graphql';
import {
InviterType,
} from './index';
const InvitationType = new GraphQLObjectType({
name: 'Invitation',
description: 'Invitation',
fields: () => ({
inviteeId: { type: GraphQLString },
acceptedDate: { type: GraphQLInt },
refusedDate: { type: GraphQLInt },
by: { type: InviterType },
}),
});
export default InvitationType;
+16
View File
@@ -0,0 +1,16 @@
import {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
} from 'graphql';
const InviterType = new GraphQLObjectType({
name: 'Inviter',
description: 'Inviter',
fields: () => ({
date: { type: GraphQLInt },
inviterId: { type: GraphQLString },
}),
});
export default InviterType;
+17
View File
@@ -0,0 +1,17 @@
import {
GraphQLObjectType,
GraphQLString,
} from 'graphql';
import ParticipantStateEnumType from './enum/ParticipantState';
const ParticipantType = new GraphQLObjectType({
name: 'Participant',
description: 'Informations about the participant of an event',
fields: () => ({
participantId: { type: GraphQLString },
state: { type: ParticipantStateEnumType },
operationId: { type: GraphQLString },
}),
});
export default ParticipantType;
+22
View File
@@ -0,0 +1,22 @@
import {
GraphQLObjectType,
GraphQLString,
GraphQLBoolean,
GraphQLID,
} from 'graphql';
const PlotterType = new GraphQLObjectType({
name: 'Plotter',
description: 'Will soon change in order to use contained plotter objects',
fields: () => ({
id: { type: GraphQLID },
ownerId: { type: GraphQLString },
isTemplate: { type: GraphQLBoolean },
name: { type: GraphQLString },
host: { type: GraphQLString },
repo: { type: GraphQLString },
moduleName: { type: GraphQLString },
}),
});
export default PlotterType;
+16
View File
@@ -0,0 +1,16 @@
import {
GraphQLObjectType,
GraphQLString,
} from 'graphql';
const PresentationType = new GraphQLObjectType({
name: 'Presentation',
description: 'Presentation page of the event',
fields: () => ({
banner: { type: GraphQLString },
profile: { type: GraphQLString },
page: { type: GraphQLString },
}),
});
export default PresentationType;
+18
View File
@@ -0,0 +1,18 @@
import {
GraphQLObjectType,
} from 'graphql';
import {
PrizeConditionType,
PrizePoolType,
} from './index';
const PrizeType = new GraphQLObjectType({
name: 'Prize',
description: 'Prize, by default in algos',
fields: () => ({
condition: { type: PrizeConditionType },
pool: { type: PrizePoolType },
}),
});
export default PrizeType;
+17
View File
@@ -0,0 +1,17 @@
import {
GraphQLInt,
GraphQLObjectType,
GraphQLString,
} from 'graphql';
const PrizeConditionType = new GraphQLObjectType({
name: 'PrizeCondition',
description: 'PrizeCondition',
fields: () => ({
from: { type: GraphQLInt },
to: { type: GraphQLInt },
additional: { type: GraphQLString },
}),
});
export default PrizeConditionType;
+16
View File
@@ -0,0 +1,16 @@
import {
GraphQLInt,
GraphQLObjectType,
GraphQLString,
} from 'graphql';
const PrizePoolType = new GraphQLObjectType({
name: 'PrizePool',
description: 'PrizePool',
fields: () => ({
amount: { type: GraphQLInt },
asset: { type: GraphQLString },
}),
});
export default PrizePoolType;
+15
View File
@@ -0,0 +1,15 @@
import {
GraphQLObjectType,
GraphQLString,
} from 'graphql';
const RuleType = new GraphQLObjectType({
name: 'Rule',
description: 'Textual rules of an event',
fields: () => ({
title: { type: GraphQLString },
description: { type: GraphQLString },
}),
});
export default RuleType;
+19
View File
@@ -0,0 +1,19 @@
import {
GraphQLEnumType,
} from 'graphql';
import { EventStateEnum } from '../../../enums/EventState';
const values = {};
EventStateEnum.forEach((EventState) => {
values[EventState] = { value: EventState };
});
const EventStateEnumType = new GraphQLEnumType({
name: 'EventStateEnum',
values,
});
export {
EventStateEnumType as default,
};
+19
View File
@@ -0,0 +1,19 @@
import {
GraphQLEnumType,
} from 'graphql';
import { HistoryTypeEnum } from '../../../enums/HistoryType';
const values = {};
HistoryTypeEnum.forEach((HistoryType) => {
values[HistoryType] = { value: HistoryType };
});
const HistoryTypeEnumType = new GraphQLEnumType({
name: 'HistoryTypeEnum',
values,
});
export {
HistoryTypeEnumType as default,
};
+19
View File
@@ -0,0 +1,19 @@
import {
GraphQLEnumType,
} from 'graphql';
import { ParticipantStateEnum } from '../../../enums/ParticipantState';
const values = {};
ParticipantStateEnum.forEach((ParticipantState) => {
values[ParticipantState] = { value: ParticipantState };
});
const ParticipantStateEnumType = new GraphQLEnumType({
name: 'ParticipantStateEnum',
values,
});
export {
ParticipantStateEnumType as default,
};
+25
View File
@@ -0,0 +1,25 @@
import PlotterType from './Plotter';
import RuleType from './Rule';
import ParticipantType from './Participant';
import PrizeType from './Prize';
import PrizeConditionType from './PrizeCondition';
import PrizePoolType from './PrizePool';
import FormulaType from './Formula';
import EventType from './Event';
import InvitationType from './Invitation';
import InviterType from './Inviter';
import PresentationType from './Presentation';
export {
PlotterType,
RuleType,
ParticipantType,
PrizeType,
PrizeConditionType,
PrizePoolType,
FormulaType,
EventType,
InvitationType,
InviterType,
PresentationType,
};
+29
View File
@@ -0,0 +1,29 @@
import {
GraphQLString,
GraphQLInt,
GraphQLInputObjectType,
GraphQLList,
} from 'graphql';
import InputPrizeType from './Prize';
import InputPresentationType from './Presentation';
import InputRuleType from './Rule';
const Type = new GraphQLInputObjectType({
name: 'EventInput',
description: 'Payload for event input',
fields: () => ({
title: { type: GraphQLString },
subtitle: { type: GraphQLString },
hostId: { type: GraphQLString },
description: { type: GraphQLString },
startDatetime: { type: GraphQLInt },
finishDatetime: { type: GraphQLInt },
formulaId: { type: GraphQLString },
plotterId: { type: GraphQLString },
prizes: { type: new GraphQLList(InputPrizeType) },
rules: { type: new GraphQLList(InputRuleType) },
presentation: { type: InputPresentationType },
}),
});
export default Type;
+15
View File
@@ -0,0 +1,15 @@
import {
GraphQLNonNull,
GraphQLString,
GraphQLInputObjectType,
} from 'graphql';
const Type = new GraphQLInputObjectType({
name: 'FormulaInput',
description: 'Payload for formula input',
fields: () => ({
name: { type: new GraphQLNonNull(GraphQLString) },
}),
});
export default Type;
+16
View File
@@ -0,0 +1,16 @@
import {
GraphQLInputObjectType,
GraphQLString,
} from 'graphql';
const Type = new GraphQLInputObjectType({
name: 'ParticipantInput',
description: 'Payload for formula input',
fields: () => ({
participantId: { type: GraphQLString },
botId: { type: GraphQLString },
releaseId: { type: GraphQLString },
}),
});
export default Type;
+18
View File
@@ -0,0 +1,18 @@
import {
GraphQLNonNull,
GraphQLString,
GraphQLInputObjectType,
} from 'graphql';
const Type = new GraphQLInputObjectType({
name: 'PlotterInput',
description: 'Payload for plotter input',
fields: () => ({
name: { type: new GraphQLNonNull(GraphQLString) },
host: { type: GraphQLString },
repo: { type: GraphQLString },
moduleName: { type: GraphQLString },
}),
});
export default Type;
+16
View File
@@ -0,0 +1,16 @@
import {
GraphQLString,
GraphQLInputObjectType,
} from 'graphql';
const Type = new GraphQLInputObjectType({
name: 'PresentationInput',
description: 'Payload for presentation input',
fields: () => ({
banner: { type: GraphQLString },
profile: { type: GraphQLString },
page: { type: GraphQLString },
}),
});
export default Type;
+16
View File
@@ -0,0 +1,16 @@
import {
GraphQLInputObjectType,
} from 'graphql';
import InputPrizeConditionType from './PrizeCondition';
import InputPrizePoolType from './PrizePool';
const Type = new GraphQLInputObjectType({
name: 'PrizeInput',
description: 'Payload for formula input',
fields: () => ({
condition: { type: InputPrizeConditionType },
pool: { type: InputPrizePoolType },
}),
});
export default Type;
+17
View File
@@ -0,0 +1,17 @@
import {
GraphQLInputObjectType,
GraphQLInt,
GraphQLString,
} from 'graphql';
const Type = new GraphQLInputObjectType({
name: 'PrizeConditionInput',
description: 'Payload for formula input',
fields: () => ({
from: { type: GraphQLInt },
to: { type: GraphQLInt },
additional: { type: GraphQLString },
}),
});
export default Type;
+16
View File
@@ -0,0 +1,16 @@
import {
GraphQLInputObjectType,
GraphQLInt,
GraphQLString,
} from 'graphql';
const Type = new GraphQLInputObjectType({
name: 'PrizePoolInput',
description: 'Payload for formula input',
fields: () => ({
amount: { type: GraphQLInt },
asset: { type: GraphQLString },
}),
});
export default Type;
+16
View File
@@ -0,0 +1,16 @@
import {
GraphQLNonNull,
GraphQLString,
GraphQLInputObjectType,
} from 'graphql';
const Type = new GraphQLInputObjectType({
name: 'RuleInput',
description: 'Payload for rule input',
fields: () => ({
title: { type: new GraphQLNonNull(GraphQLString) },
description: { type: GraphQLString },
}),
});
export default Type;
+17
View File
@@ -0,0 +1,17 @@
import PlotterInputType from './Plotter';
import RuleInputType from './Rule';
import PrizeInputType from './Prize';
import FormulaInputType from './Formula';
import EventInputType from './Event';
import ParticipantInputType from './Participant';
import PresentationInputType from './Presentation';
export {
PlotterInputType,
RuleInputType,
PrizeInputType,
FormulaInputType,
EventInputType,
ParticipantInputType,
PresentationInputType,
};
+19
View File
@@ -0,0 +1,19 @@
export const capitalize = string => (string).charAt(0).toUpperCase() + (string).slice(1);
export const slugify = text => text.toString().toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w-]+/g, '')
.replace(/--+/g, '-')
.replace(/^-+/, '')
.replace(/-+$/, '');
export const epoch = () => Math.round(new Date().getTime() / 1000);
export const isBetween = (value, valA, valB) => {
const min = valA < valB ? valA : valB;
const max = valA > valB ? valA : valB;
if (value >= min && value <= max) {
return true;
}
return false;
};