Merge pull request #1 from nikolabjelo/master

Fully functional backend, minimal frontend
This commit is contained in:
Luis Fernando Molina authored and GitHub committed 2018-10-29 19:17:51 +01:00
commit 45a26b5521
59 files changed
+10523

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Optional npm cache directory
.npm
# Visual Studio Code
.vscode
#Mac specific files
.DS_Store
+3
View File
@@ -0,0 +1,3 @@
build
node_modules
.DS_Store
+3094
View File
File diff suppressed because it is too large. Load diff
+31
View File
@@ -0,0 +1,31 @@
{
"name": "@advancedalgos/hosts-client",
"version": "0.0.1",
"description": "Advanced Algos Host client-side web app",
"author": "",
"license": "",
"main": "src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"standard": {
"parser": "babel-eslint"
},
"devDependencies": {
"babel-eslint": "^10.0.1",
"react-hot-loader": "^4.3.11",
"standard": "^12.0.1"
},
"dependencies": {
"@advancedalgos/web-components": "0.0.13",
"@material-ui/core": "^3.2.0",
"@material-ui/icons": "^3.0.1",
"classnames": "^2.2.6",
"graphql-tag": "^2.10.0",
"luxon": "^1.4.4",
"material-ui-pickers": "^1.0.1",
"react": "^16.5.2",
"react-apollo": "^2.2.4",
"react-router-dom": "^4.3.1"
}
}
@@ -0,0 +1,99 @@
import React from 'react'
import { Link } from 'react-router-dom'
import {
Grid, Paper,
Typography,
Button
} from '@material-ui/core'
import { withStyles } from '@material-ui/core/styles'
const styles = theme => ({
root: {
flexGrow: 1,
padding: 20,
margin: 10
},
image: {
width: 128,
height: '100%',
cursor: 'default'
},
img: {
margin: 'auto',
display: 'block',
maxWidth: '100%',
maxHeight: '100%'
},
buttonList: {
margin: theme.spacing.unit,
float: 'right'
},
buttonGrid: {
marginTop: -20
}
})
class Event extends React.Component {
render () {
const classes = this.props.classes
const {
name,
designator,
startDatetime,
finishDatetime,
host,
description
} = this.props.event
return (
<Paper className={classes.root}>
<Grid container spacing={16}>
<Grid item xs>
<Typography gutterBottom variant='headline'> {name} </Typography>
<Typography gutterBottom>From : {startDatetime} </Typography>
<Typography gutterBottom>To : {finishDatetime} </Typography>
</Grid>
<Grid item xs>
<Typography gutterBottom>Hosted by: {host.alias} ({host.lastName} {host.firstName}) </Typography>
<Typography gutterBottom>Formula: </Typography>
<Typography gutterBottom>First prize: </Typography>
</Grid>
<Grid item xs={12} sm container>
<Grid item xs container direction='column' spacing={16}>
<Grid item xs>
<Typography gutterBottom variant='headline'> Description : </Typography>
<Typography gutterBottom> {description} </Typography>
</Grid>
<Grid item className={classes.buttonGrid}>
<Button
className={classes.buttonList}
variant='outlined'
color='primary'
size='small'
component={Link}
to={'/hosted-events/' + designator}
>
Edit
</Button>
<Button
className={classes.buttonList}
variant='outlined'
color='primary'
size='small'
component={Link}
to={'/events/' + designator}
>
Show
</Button>
</Grid>
</Grid>
</Grid>
</Grid>
</Paper>
)
}
}
export default withStyles(styles)(Event)
+98
View File
@@ -0,0 +1,98 @@
import React from 'react'
import { Mutation } from 'react-apollo'
import { HOSTS_HOSTEVENT, HOSTS_EVENTSBYHOST } from './graphql'
import { DateTime } from 'luxon'
import {
Button,
TextField
} from '@material-ui/core'
import { ChevronLeft, ChevronRight } from '@material-ui/icons'
import { DateTimePicker } from 'material-ui-pickers'
class New extends React.Component {
constructor (props) {
super(props)
this.state = {
name: '',
description: '',
startDatetime: DateTime.local().plus({ days: 1 }).startOf('day'),
finishDatetime: DateTime.local().plus({ days: 8 }).startOf('day')
}
}
render () {
const { name, description, startDatetime, finishDatetime } = this.state
return (
<Mutation mutation={HOSTS_HOSTEVENT}
update={(store, { data }) => {
const { hosts_EventsByHost: hostedEvents } = store.readQuery({ query: HOSTS_EVENTSBYHOST })
store.writeQuery({
query: HOSTS_EVENTSBYHOST,
data: { hosts_EventsByHost: hostedEvents.concat([data.hosts_HostEvent]) }
})
}
}
>
{(hostEvent, { data }) => (
<div className='container'>
<form
onSubmit={e => {
e.preventDefault()
hostEvent({ variables: {
name: name,
description: description,
startDatetime: startDatetime.valueOf() / 1000,
finishDatetime: startDatetime.valueOf() / 1000
} })
this.props.handleNewEventClose()
}}
>
<TextField
label='Name'
value={name}
onChange={(e) => this.setState({ name: e.target.value })}
fullWidth
/>
<TextField
multiline
label='Description'
value={description}
onChange={(e) => this.setState({ description: e.target.value })}
fullWidth
/>
<DateTimePicker
autoOk
disablePast
format="DD' at 'HH:mm"
ampm={false}
showTabs={false}
leftArrowIcon={<ChevronLeft />}
rightArrowIcon={<ChevronRight />}
value={startDatetime}
onChange={(date) => this.setState({ startDatetime: date })}
helperText='Competition start date'
/>
<DateTimePicker
autoOk
disablePast
format="DD' at 'HH:mm"
ampm={false}
showTabs={false}
leftArrowIcon={<ChevronLeft />}
rightArrowIcon={<ChevronRight />}
value={finishDatetime}
onChange={(date) => this.setState({ finishDatetime: date })}
helperText='Competition finishing date'
/>
<Button type='submit' variant='contained' color='secondary'>Create New Project</Button>
</form>
<div className='form-close' onClick={() => this.clearTempStates()} />
</div>
)}
</Mutation>
)
}
}
export default New
@@ -0,0 +1,29 @@
import gql from 'graphql-tag'
const fragments = `
name
designator
startDatetime
finishDatetime
host {
alias
firstName
lastName
}
description
`
export const HOSTS_HOSTEVENT = gql`
mutation Hosts_HostEvent($name: String!, $description: String!, $startDatetime: Int!, $finishDatetime: Int!) {
hosts_HostEvent(name: $name, description: $description, startDatetime: $startDatetime, finishDatetime: $finishDatetime) {
${fragments}
}
}
`
export const HOSTS_EVENTSBYHOST = gql`
query Hosts_EventsByHost{
hosts_EventsByHost {
${fragments}
}
}
`
@@ -0,0 +1,85 @@
import React from 'react'
import { Query } from 'react-apollo'
import { HOSTS_EVENTSBYHOST } from './graphql'
import {
Button,
Dialog,
DialogContent,
DialogContentText,
DialogTitle
} from '@material-ui/core'
import { withStyles } from '@material-ui/core/styles'
import styles from './styles'
import New from './New'
import Event from './Event'
class HostedEvent extends React.Component {
constructor (props) {
super(props)
this.state = {
isNewEventOpen: false
}
}
handleNewEventOpen = () => {
this.setState({ isNewEventOpen: true })
};
handleNewEventClose = () => {
this.setState({ isNewEventOpen: false })
};
render () {
const { classes } = this.props
return (
<React.Fragment>
<Query
query={HOSTS_EVENTSBYHOST}
>
{({ loading, error, data }) => {
if (loading) return 'Loading...'
if (error) return `Error! ${error.message}`
const list = data.hosts_EventsByHost.map((event, index) => {
return (
<Event key={index} event={event} />
)
})
return (
<React.Fragment>
{ list }
</React.Fragment>
)
}}
</Query>
<React.Fragment>
<Button variant='contained' color='secondary'
aria-label='addNewEvent' className={classes.centered}
onClick={this.handleNewEventOpen} >
Host another event
</Button>
<Dialog
open={this.state.isNewEventOpen}
onClose={this.handleNewEventClose}
aria-labelledby='addEvent-dialog-title'
>
<DialogTitle id='addEvent-dialog-title'>
Host an event
</DialogTitle>
<DialogContent>
<DialogContentText>
Here you will add just the minimal information, will be settable in the edit page of your event.
</DialogContentText>
<New handleNewEventClose={this.handleNewEventClose} classes={classes} />
</DialogContent>
</Dialog>
</React.Fragment>
</React.Fragment>
)
}
}
export default withStyles(styles)(HostedEvent)
@@ -0,0 +1,10 @@
const styles = theme => ({
centered: {
display: 'block',
marginLeft: 'auto',
marginRight: 'auto'
}
})
export default styles
+124
View File
@@ -0,0 +1,124 @@
import React from 'react'
import { toLocalTime } from '../../utils'
import {
Grid, Paper, Typography, Button,
Dialog, DialogContent, DialogContentText, DialogTitle
} from '@material-ui/core'
import { withStyles } from '@material-ui/core/styles'
const styles = theme => ({
root: {
flexGrow: 1,
padding: 20,
margin: 10
},
image: {
width: 128,
height: '100%',
cursor: 'default'
},
img: {
margin: 'auto',
display: 'block',
maxWidth: '100%',
maxHeight: '100%'
},
buttonList: {
margin: theme.spacing.unit,
float: 'right'
},
buttonGrid: {
marginTop: -20
}
})
class Competition extends React.Component {
render () {
const classes = this.props.classes
const { displayName,
startDatetime,
finishDatetime,
host,
description,
formula,
prizes
} = this.props.competition
const firstPrice = prizes.find(prize => {
return prize.position === 1
})
return (
<Paper className={classes.root}>
<Grid container spacing={16}>
<Grid item xs>
<Typography gutterBottom variant='headline'> { displayName } </Typography>
<Typography gutterBottom>From : {toLocalTime(startDatetime)} </Typography>
<Typography gutterBottom>To : {toLocalTime(finishDatetime)} </Typography>
</Grid>
<Grid item xs>
<Typography gutterBottom>Hosted by: { host }</Typography>
<Typography gutterBottom>Formula: { formula }</Typography>
<Typography gutterBottom>First prize: { firstPrice ? firstPrice.algoPrize + ' ALGOS' : 'none' }</Typography>
</Grid>
<Grid item xs={12} sm container>
<Grid item xs container direction='column' spacing={16}>
<Grid item xs>
<Typography gutterBottom variant='headline'> Description : </Typography>
<Typography gutterBottom>{ description }</Typography>
</Grid>
<Grid item className={classes.buttonGrid}>
<Button
className={classes.buttonList}
variant='outlined' color='primary' size='small'
onClick={() => this.auditLog()}
>Apply</Button>
<Button
className={classes.buttonList}
variant='outlined' color='primary' size='small'
onClick={() => this.editKey()}
>Get details</Button>
<Button
className={classes.buttonList}
variant='outlined' color='primary' size='small'
onClick={() => this.editKey()}
>Edit</Button>
<Dialog
aria-labelledby='addKey-dialog-title'
>
<DialogTitle id='addKey-dialog-title'>
Edit Key
</DialogTitle>
<DialogContent>
<DialogContentText>
You will need to complete this form with the information from
the exchange.
</DialogContentText>
<p> some stuff </p>
</DialogContent>
</Dialog>
<Dialog
aria-labelledby='auditLog-dialog-title'
>
<DialogTitle id='auditLog-dialog-title'>
Audit Log History
</DialogTitle>
<DialogContent>
<p> some stuff </p>
</DialogContent>
</Dialog>
</Grid>
</Grid>
</Grid>
</Grid>
</Paper>
)
}
}
export default withStyles(styles)(Competition)
+67
View File
@@ -0,0 +1,67 @@
import React from 'react'
import gql from 'graphql-tag'
import { Query } from 'react-apollo'
import Typography from '@material-ui/core/Typography'
import { withStyles } from '@material-ui/core/styles'
import Competition from './Competition'
import styles from './styles'
const HOST_COMPETITIONS = gql`
query Hosts_Competitions{
hosts_Competitions {
displayName
host
startDatetime
finishDatetime
description
formula
participants {
devTeam
}
prizes {
position
algoPrize
}
}
}
`
class Search extends React.Component {
render () {
return (
<React.Fragment>
<Typography
variant='display1'
align='center'
color='textPrimary'
gutterBottom
>
Enroll in an competition
</Typography>
<Query
query={HOST_COMPETITIONS}
>
{({ loading, error, data }) => {
if (loading) return 'Loading...'
if (error) return `Error! ${error.message}`
const list = data.hosts_Competitions.map((competition, index) => {
return (
<Competition key={index} competition={competition} />
)
})
return (
<React.Fragment>
{ list }
</React.Fragment>
)
}}
</Query>
</React.Fragment>
)
}
}
export default withStyles(styles)(Search)
+4
View File
@@ -0,0 +1,4 @@
const styles = theme => ({
})
export default styles
+11
View File
@@ -0,0 +1,11 @@
import GamesIcon from '@material-ui/icons/Games'
import SearchIcon from '@material-ui/icons/Search'
import LibraryAddIcon from '@material-ui/icons/LibraryAdd'
const data = [
{ title: 'Look for an event', to: '/', icon: SearchIcon, text: '' },
{ title: 'Events you are enrolled in', to: '/events', icon: GamesIcon, text: '' },
{ title: 'Host your own competition', to: '/hosted-events', icon: LibraryAddIcon, text: '' }
]
export default data
+45
View File
@@ -0,0 +1,45 @@
import React from 'react'
import { Link } from 'react-router-dom'
import classNames from 'classnames'
import AppBar from '@material-ui/core/AppBar'
import Toolbar from '@material-ui/core/Toolbar'
import Typography from '@material-ui/core/Typography'
import Button from '@material-ui/core/Button'
import { withStyles } from '@material-ui/core/styles'
import datas from './data'
import styles from './styles'
const TopBar = ({ classes, user, match }) => {
const buttons = datas.map((data, index) => {
const Icon = data.icon
return (
<Button
key={index}
variant='text'
size='small'
className={classNames(classes.button, classes.cssRoot)}
title={data.title}
component={Link}
to={data.to}>
<Icon className={classNames(classes.leftIcon, classes.iconSmall)} />
{data.text}
</Button>)
}
)
return (
<div className={classes.root}>
<AppBar position='static' color='secondary'>
<Toolbar>
<Typography variant='h5' color='inherit' className={classes.flex}>
Manage competition
</Typography>
{buttons}
</Toolbar>
</AppBar>
</div>
)
}
export default withStyles(styles)(TopBar)
+37
View File
@@ -0,0 +1,37 @@
const styles = theme => ({
root: {
flexGrow: 1
},
flex: {
flexGrow: 1,
marginLeft: 30
},
menuButton: {
marginLeft: -12,
marginRight: 20
},
cssRoot: {
color: '#FFFFFF',
backgroundColor: theme.palette.secondary,
'&:hover': {
backgroundColor: theme.palette.dark
},
whiteSpace: 'nowrap',
paddingRight: 2 * theme.spacing.unit,
paddingLeft: 2 * theme.spacing.unit
},
button: {
margin: theme.spacing.unit
},
leftIcon: {
marginRight: theme.spacing.unit
},
rightIcon: {
marginLeft: theme.spacing.unit
},
iconSmall: {
fontSize: 20
}
})
export default styles
+53
View File
@@ -0,0 +1,53 @@
import React, { Component } from 'react'
import { Route, BrowserRouter, Switch } from 'react-router-dom'
import { MuiPickersUtilsProvider } from 'material-ui-pickers'
import LuxonUtils from 'material-ui-pickers/utils/luxon-utils'
import { getItem } from './utils/local-storage'
import TopBar from './Components/TopBar'
import Search from './Components/Search'
import HostedEvent from './Components/HostedEvent'
class App extends Component {
constructor (props) {
super(props)
this.state = {
user: null
}
}
async componentDidMount () {
let user = await getItem('user')
if (user !== null && user !== undefined && user !== 'undefined') {
user = JSON.parse(user)
this.setState({ user })
}
}
render () {
let loggedIn
if (this.state.user !== null) {
loggedIn = (<TopBar match={this.props.match} user={this.state.user} />)
} else {
loggedIn = ''
}
return (
<MuiPickersUtilsProvider utils={LuxonUtils}>
<BrowserRouter basename={this.props.match.path}>
<div>
{loggedIn}
<Switch>
<Route exact path='/' component={Search} />
<Route path='/hosted-events' component={HostedEvent} />
</Switch>
</div>
</BrowserRouter>
</MuiPickersUtilsProvider>
)
}
}
export default App
+6
View File
@@ -0,0 +1,6 @@
export const toLocalTime = (epoch) => {
let localDate = new Date(0)
localDate.setUTCSeconds(epoch)
var options = { year: 'numeric', month: 'long', day: '2-digit' }
return localDate.toLocaleDateString(options) + ' ' + localDate.toLocaleTimeString('en-US')
}
+9
View File
@@ -0,0 +1,9 @@
const getItem = async name => window.localStorage.getItem(name)
const setItem = async (name, value) => window.localStorage.setItem(name, value)
const removeItem = async name => window.localStorage.removeItem(name)
export {
getItem,
setItem,
removeItem
}
+3
View File
@@ -0,0 +1,3 @@
{
"presets": ["env", "stage-2"]
}
+8
View File
@@ -0,0 +1,8 @@
PORT=3000
DB_USERNAME=example_name
DB_PASSWORD=example_password
DB_DOMAIN=example.com:1234/example_name
SENTRY_DNS=https://some-val@sentry.io/some-id
TEAMS_ENDPOINT=https://teams-api.advancedalgos.net/graphql/
+23
View File
@@ -0,0 +1,23 @@
# 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
+5277
View File
File diff suppressed because it is too large. Load diff
+34
View File
@@ -0,0 +1,34 @@
{
"name": "hosts-server",
"version": "0.1.0",
"description": "Advanced Algos Host backend API",
"author": "",
"license": "",
"main": "src/index.js",
"scripts": {
"start": "nodemon --exec babel-node --presets env,stage-2 src/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"standard": {
"ignore": [
"/src/errors/index.js"
]
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-stage-2": "^6.24.1",
"nodemon": "^1.18.4"
},
"dependencies": {
"@sentry/node": "^4.1.1",
"axios": "^0.18.0",
"cors": "^2.8.4",
"dotenv": "^6.0.0",
"express": "^4.16.3",
"express-graphql": "^0.6.12",
"graphql": "^14.0.0",
"graphql-playground-middleware-express": "^1.7.6",
"mongoose": "^5.3.4"
}
}
+19
View File
@@ -0,0 +1,19 @@
export class AuthentificationError extends Error {
code = 401
message = 'Autentification not found, you have to be authentificated to perform this action'
}
export class DatabaseError extends Error {
code = 404
message = 'Ressource not found : ' + this.message
}
export class WrongArgumentsError extends Error {
code = 400
message = 'Wrong arguments : ' + this.message
}
export class ServiceUnavailableError extends Error {
code = 503
message = 'At least one service is unresponding ' + this.message
}
+55
View File
@@ -0,0 +1,55 @@
import express from 'express'
import 'dotenv/config'
import cors from 'cors'
import mongoose from 'mongoose'
import graphqlHTTP from 'express-graphql'
import expressPlayground from 'graphql-playground-middleware-express'
import schema from './schema'
import * as Sentry from '@sentry/node'
// Initialise express
const app = express()
// Initialising sentry
Sentry.init({ dsn: process.env.SENTRY_DNS })
app.use(Sentry.Handlers.requestHandler())
// Allow cross origing request
app.use(cors())
/* -------------------------------------------------
---------------- Database setup --------------------
------------------------------------------------- */
// Database Connection
mongoose.connect(`mongodb://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@${process.env.DB_DOMAIN}`, { useNewUrlParser: true })
// Get Mongoose to use the global promise library
mongoose.Promise = global.Promise
// Get the default connection
var db = mongoose.connection
// bind error and success to console log
db.on('error', () => { console.error.bind(console, 'MongoDB connection error:') })
db.once('open', () => { console.log('Connected to the DB.') })
/* -------------------------------------------------
----------------- Graphql setup --------------------
------------------------------------------------- */
app.use('/graphql', graphqlHTTP(req => {
return {
schema: schema,
context: {
userId: req.headers.userid,
authorization: req.headers.authorization
}
}
}))
app.get('/playground', expressPlayground({ endpoint: '/graphql' }))
// Sentry error handling middleware
app.use(Sentry.Handlers.errorHandler())
app.listen(process.env.PORT, () => {
console.log(`Listening on port ${process.env.PORT}`)
})
+46
View File
@@ -0,0 +1,46 @@
import mongoose, { Schema } from 'mongoose'
import Plotter from './plotter'
import Formula from './formula'
const eventSchema = new Schema({
designator: { type: String, required: true },
name: { type: String, required: true },
hostId: { type: String, required: true },
description: String,
startDatetime: { type: Number, required: true },
finishDatetime: { type: Number, required: true },
formula: { type: Schema.Types.ObjectId, ref: Formula.modelName },
plotter: { type: Schema.Types.ObjectId, ref: Plotter.modelName },
rules: [{
position: { type: Number, required: true },
title: { type: String, required: true },
description: String
}],
prizes: [{
rank: { type: Number, required: true },
amount: { type: Number, required: true },
additional: [{
condition: String,
amount: { type: Number, required: true },
asset: { type: String, required: true }
}]
}],
participants: [{
teamId: { type: String, required: true },
botId: String,
releaseId: String
}]
})
eventSchema.pre('find', function () {
this.populate('formula').populate('plotter')
})
eventSchema.post('save', function (doc, next) {
doc.populate('formula').populate('plotter').execPopulate().then(function () {
next()
})
})
const Event = mongoose.model('Event', eventSchema)
export default Event
+11
View File
@@ -0,0 +1,11 @@
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
}
+14
View File
@@ -0,0 +1,14 @@
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
+59
View File
@@ -0,0 +1,59 @@
import {
GraphQLNonNull,
GraphQLID,
GraphQLInt
} from 'graphql'
import {
AuthentificationError,
DatabaseError,
WrongArgumentsError
} from '../../errors'
import { EventType } from '../types'
import { Event } from '../../models'
const args = {
eventDesignator: { type: new GraphQLNonNull(GraphQLID) },
rank: { type: new GraphQLNonNull(GraphQLInt) },
amount: { type: new GraphQLNonNull(GraphQLInt) }
}
const resolve = (parent, { eventDesignator, rank, amount }, context) => {
const hostId = context.userId
if (!hostId) {
throw new AuthentificationError()
}
return new Promise((resolve, reject) => {
Event.findOne({ designator: eventDesignator, hostId }).exec((err, event) => {
if (err) {
reject(err)
} else if (!event) {
reject(new DatabaseError('None of the events you own respond to that designator'))
} else {
if (event.prizes.some(prize => prize.rank === rank)) {
reject(new WrongArgumentsError('A prize for that rank already exists'))
} else {
event.prizes.push({
rank,
amount
})
event.save((err) => {
if (err) reject(err)
else {
resolve(event)
}
})
}
}
})
})
}
const mutation = {
addPrize: {
type: EventType,
args,
resolve
}
}
export default mutation
+64
View File
@@ -0,0 +1,64 @@
import {
GraphQLNonNull,
GraphQLID,
GraphQLString
} from 'graphql'
import {
AuthentificationError,
DatabaseError,
WrongArgumentsError
} from '../../errors'
import { EventType } from '../types'
import { Event } from '../../models'
const args = {
eventDesignator: { type: new GraphQLNonNull(GraphQLID) },
title: { type: new GraphQLNonNull(GraphQLString) },
description: { type: new GraphQLNonNull(GraphQLString) }
}
const resolve = (parent, { eventDesignator, title, description }, context) => {
const hostId = context.userId
if (!hostId) {
throw new AuthentificationError()
}
return new Promise((resolve, reject) => {
Event.findOne({ designator: eventDesignator, hostId }).exec((err, event) => {
if (err) {
reject(err)
} else if (!event) {
reject(new DatabaseError('None of the events you own respond to that designator'))
} else {
if (event.rules.some(rule => rule.title === title)) {
reject(new WrongArgumentsError('A prize for that rank already exists'))
} else {
let position = 1
while (event.rules.some(rule => rule.position === position)) {
position++
}
event.rules.push({
position,
title,
description
})
event.save((err) => {
if (err) reject(err)
else {
resolve(event)
}
})
}
}
})
})
}
const mutation = {
addRule: {
type: EventType,
args,
resolve
}
}
export default mutation
@@ -0,0 +1,52 @@
import {
GraphQLNonNull,
GraphQLString
} from 'graphql'
import { AuthentificationError, DatabaseError } from '../../errors'
import { EventType } from '../types'
import { Event, Formula } from '../../models'
const args = {
eventDesignator: { type: new GraphQLNonNull(GraphQLString) },
name: { type: new GraphQLNonNull(GraphQLString) }
}
const resolve = (parent, { name, eventDesignator }, context) => {
const ownerId = context.userId
if (!ownerId) {
throw new AuthentificationError()
}
let newFormula = new Formula({ name, ownerId })
return new Promise((resolve, reject) => {
Event.findOne({ designator: eventDesignator, hostId: ownerId }).exec((err, event) => {
if (err) {
reject(err)
} else if (!event) {
reject(new DatabaseError('None of the events you own respond to that designator'))
} else {
newFormula.save((err) => {
if (err) reject(err)
else {
}
})
event.formula = newFormula._id
event.save((err) => {
if (err) reject(err)
else {
resolve(event)
}
})
}
})
})
}
const mutation = {
createAndSetFormula: {
type: EventType,
args,
resolve
}
}
export default mutation
@@ -0,0 +1,55 @@
import {
GraphQLNonNull,
GraphQLString
} from 'graphql'
import { AuthentificationError, DatabaseError } from '../../errors'
import { EventType } from '../types'
import { Event, Plotter } from '../../models'
const args = {
eventDesignator: { type: new GraphQLNonNull(GraphQLString) },
name: { type: new GraphQLNonNull(GraphQLString) },
host: { type: new GraphQLNonNull(GraphQLString) },
repo: { type: new GraphQLNonNull(GraphQLString) },
moduleName: { type: new GraphQLNonNull(GraphQLString) }
}
const resolve = (parent, { name, host, repo, moduleName, eventDesignator }, context) => {
const ownerId = context.userId
if (!ownerId) {
throw new AuthentificationError()
}
let newPlotter = new Plotter({ name, host, repo, moduleName, ownerId })
return new Promise((resolve, reject) => {
Event.findOne({ designator: eventDesignator, hostId: ownerId }).exec((err, event) => {
if (err) {
reject(err)
} else if (!event) {
reject(new DatabaseError('None of the events you own respond to that designator'))
} else {
newPlotter.save((err) => {
if (err) reject(err)
else {
}
})
event.plotter = newPlotter._id
event.save((err) => {
if (err) reject(err)
else {
resolve(event)
}
})
}
})
})
}
const mutation = {
createAndSetPlotter: {
type: EventType,
args,
resolve
}
}
export default mutation
@@ -0,0 +1,37 @@
import {
GraphQLNonNull,
GraphQLString
} from 'graphql'
import { AuthentificationError } from '../../errors'
import { FormulaType } from '../types'
import { Formula } from '../../models'
const args = {
name: { type: new GraphQLNonNull(GraphQLString) }
}
const resolve = (parent, { name }, context) => {
const ownerId = context.userId
if (!ownerId) {
throw new AuthentificationError()
}
let newFormula = new Formula({ name, ownerId })
return new Promise((resolve, reject) => {
newFormula.save((err) => {
if (err) reject(err)
else {
resolve(newFormula)
}
})
})
}
const mutation = {
createFormula: {
type: FormulaType,
args,
resolve
}
}
export default mutation
@@ -0,0 +1,40 @@
import {
GraphQLNonNull,
GraphQLString
} from 'graphql'
import { AuthentificationError } from '../../errors'
import { PlotterType } from '../types'
import { Plotter } from '../../models'
const args = {
name: { type: new GraphQLNonNull(GraphQLString) },
host: { type: new GraphQLNonNull(GraphQLString) },
repo: { type: new GraphQLNonNull(GraphQLString) },
moduleName: { type: new GraphQLNonNull(GraphQLString) }
}
const resolve = (parent, { name, host, repo, moduleName }, context) => {
const ownerId = context.userId
if (!ownerId) {
throw new AuthentificationError()
}
let newPlotter = new Plotter({ name, host, repo, moduleName, ownerId })
return new Promise((resolve, reject) => {
newPlotter.save((err) => {
if (err) reject(err)
else {
resolve(newPlotter)
}
})
})
}
const mutation = {
createPlotter: {
type: PlotterType,
args,
resolve
}
}
export default mutation
+59
View File
@@ -0,0 +1,59 @@
import {
GraphQLNonNull,
GraphQLID,
GraphQLInt,
GraphQLString
} from 'graphql'
import { AuthentificationError, DatabaseError } from '../../errors'
import { EventType } from '../types'
import { Event } from '../../models'
const args = {
designator: { type: new GraphQLNonNull(GraphQLID) },
name: { type: GraphQLString },
description: { type: GraphQLString },
startDatetime: { type: GraphQLInt },
finishDatetime: { type: GraphQLInt },
formulaId: { type: GraphQLString },
plotterId: { type: GraphQLString }
}
const resolve = (parent, { designator, name, description, startDatetime, finishDatetime, formulaId, plotterId }, context) => {
const hostId = context.userId
if (!hostId) {
throw new AuthentificationError()
}
return new Promise((resolve, reject) => {
Event.findOne({ designator, hostId }).exec((err, event) => {
if (err) {
reject(err)
} else if (!event) {
reject(new DatabaseError('None of the events you own respond to that designator'))
} else {
event.name = name || event.name
event.description = description || event.description
event.startDatetime = startDatetime || event.startDatetime
event.finishDatetime = finishDatetime || event.finishDatetime
event.formula = formulaId || event.formula
event.plotter = plotterId || event.plotter
event.save((err) => {
if (err) reject(err)
else {
resolve(event)
}
})
}
})
})
}
const mutation = {
editEvent: {
type: EventType,
args,
resolve
}
}
export default mutation
@@ -0,0 +1,87 @@
import {
GraphQLNonNull,
GraphQLID,
GraphQLString
} from 'graphql'
import axios from 'axios'
import {
AuthentificationError,
WrongArgumentsError,
ServiceUnavailableError
} from '../../errors'
import { EventType } from '../types'
import { Event } from '../../models'
const args = {
eventDesignator: { type: new GraphQLNonNull(GraphQLID) },
teamId: { type: new GraphQLNonNull(GraphQLString) },
botId: { type: GraphQLString },
releaseId: { type: GraphQLString }
}
const resolve = (parent, { eventDesignator, teamId, botId, releaseId }, context) => {
const userid = context.userId
if (!userid) {
throw new AuthentificationError()
}
return new Promise((resolve, reject) => {
axios({
url: process.env.TEAMS_ENDPOINT,
method: 'post',
data: {
query: `
{
teamsByRole{
id
}
}
`
},
headers: {
userid,
authorization: context.authorization
}
}).then(
(result) => {
if (!result.data.data.teamsByRole.some(team => team.id === teamId)) {
reject(new WrongArgumentsError('You are not eligible to register this team'))
return
}
Event.findOne({ designator: eventDesignator }).exec((err, event) => {
if (err) reject(err)
else {
let participantIndex
event.participants.find((participant, index) => {
if (participant.teamId === teamId) {
participantIndex = index
}
})
event.participants[participantIndex].botId = botId || event.participants[participantIndex].botId
event.participants[participantIndex].releaseId = releaseId || event.participants[participantIndex].releaseId
event.save((err) => {
if (err) reject(err)
else {
resolve(event)
}
})
}
})
},
(error) => {
reject(new ServiceUnavailableError(error))
}
)
})
}
const mutation = {
editParticipant: {
type: EventType,
args,
resolve
}
}
export default mutation
+58
View File
@@ -0,0 +1,58 @@
import {
GraphQLNonNull,
GraphQLID,
GraphQLInt
} from 'graphql'
import { AuthentificationError, DatabaseError } from '../../errors'
import { EventType } from '../types'
import { Event } from '../../models'
const args = {
eventDesignator: { type: new GraphQLNonNull(GraphQLID) },
rank: { type: new GraphQLNonNull(GraphQLInt) },
amount: { type: GraphQLInt }
}
const resolve = (parent, { eventDesignator, rank, amount }, context) => {
const hostId = context.userId
if (!hostId) {
throw new AuthentificationError()
}
return new Promise((resolve, reject) => {
Event.findOne({ designator: eventDesignator, hostId }).exec((err, event) => {
if (err) {
reject(err)
} else if (!event) {
reject(new DatabaseError('None of the events you own respond to that designator'))
} else {
let prizeIndex = null
event.prizes.find((prize, index) => {
if (prize.rank === rank) {
prizeIndex = index
}
})
if (!prizeIndex) {
reject(new DatabaseError('There is no prize for that index'))
return
}
event.prizes[prizeIndex].amount = amount || event.prizes[prizeIndex].amount
event.save((err) => {
if (err) reject(err)
else {
resolve(event)
}
})
}
})
})
}
const mutation = {
editPrize: {
type: EventType,
args,
resolve
}
}
export default mutation
+65
View File
@@ -0,0 +1,65 @@
import {
GraphQLNonNull,
GraphQLID,
GraphQLString
} from 'graphql'
import { AuthentificationError, DatabaseError, WrongArgumentsError } from '../../errors'
import { EventType } from '../types'
import { Event } from '../../models'
const args = {
eventDesignator: { type: new GraphQLNonNull(GraphQLID) },
title: { type: new GraphQLNonNull(GraphQLString) },
newtitle: { type: GraphQLString },
description: { type: GraphQLString }
}
const resolve = (parent, { eventDesignator, title, newtitle, description }, context) => {
const hostId = context.userId
if (!hostId) {
throw new AuthentificationError()
}
return new Promise((resolve, reject) => {
Event.findOne({ designator: eventDesignator, hostId }).exec((err, event) => {
if (err) {
reject(err)
} else if (!event) {
reject(new DatabaseError('None of the events you own respond to that designator'))
} else {
let ruleIndex = null
event.rules.find((rule, index) => {
if (rule.title === title) {
ruleIndex = index
}
})
if (!ruleIndex) {
reject(new DatabaseError('There is no rule with that title'))
return
}
event.rules[ruleIndex].description = description || event.rules[ruleIndex].description
if (event.rules.some(rule => rule.title === newtitle)) {
reject(new WrongArgumentsError('There is already a rule using your new title'))
} else {
event.rules[ruleIndex].title = newtitle || event.rules[ruleIndex].title
}
event.save((err) => {
if (err) reject(err)
else {
resolve(event)
}
})
}
})
})
}
const mutation = {
editRule: {
type: EventType,
args,
resolve
}
}
export default mutation
+49
View File
@@ -0,0 +1,49 @@
import {
GraphQLNonNull,
GraphQLInt,
GraphQLString
} from 'graphql'
import { AuthentificationError } from '../../errors'
import { EventType } from '../types'
import { Event } from '../../models'
import { slugify } from '../../utils/functions'
const args = {
name: { type: new GraphQLNonNull(GraphQLString) },
description: { type: new GraphQLNonNull(GraphQLString) },
startDatetime: { type: new GraphQLNonNull(GraphQLInt) },
finishDatetime: { type: new GraphQLNonNull(GraphQLInt) }
}
const resolve = (parent, { name, description, startDatetime, finishDatetime }, context) => {
const hostId = context.userId
if (!hostId) {
throw new AuthentificationError()
}
let newEvent = new Event({
hostId,
name,
description,
startDatetime,
finishDatetime
})
newEvent.designator = slugify(newEvent.name) + '-' + newEvent._id
return new Promise((resolve, reject) => {
newEvent.save((err) => {
if (err) reject(err)
else {
resolve(newEvent)
}
})
})
}
const mutation = {
hostEvent: {
type: EventType,
args,
resolve
}
}
export default mutation
@@ -0,0 +1,87 @@
import 'dotenv/config'
import {
GraphQLNonNull,
GraphQLID,
GraphQLString
} from 'graphql'
import axios from 'axios'
import {
AuthentificationError,
WrongArgumentsError,
ServiceUnavailableError
} from '../../errors'
import { EventType } from '../types'
import { Event } from '../../models'
const args = {
designator: { type: new GraphQLNonNull(GraphQLID) },
teamId: { type: new GraphQLNonNull(GraphQLString) },
botId: { type: GraphQLString },
releaseId: { type: GraphQLString }
}
const resolve = (parent, { designator, teamId, botId, releaseId }, context) => {
const userid = context.userId
if (!userid) {
throw new AuthentificationError()
}
return new Promise((resolve, reject) => {
axios({
url: process.env.TEAMS_ENDPOINT,
method: 'post',
data: {
query: `
{
teamsByRole{
id
}
}
`
},
headers: {
userid,
authorization: context.authorization
}
}).then(
(result) => {
if (!result.data.data.teamsByRole.some(team => team.id === teamId)) {
reject(new WrongArgumentsError('You are not eligible to register this team'))
return
}
Event.findOne({ designator }).exec((err, event) => {
if (err) reject(err)
else {
if (event.participants.some(participant => participant.teamId === teamId)) {
reject(new WrongArgumentsError('You are already registred'))
} else {
event.participants.push({
teamId,
botId,
releaseId
})
event.save((err) => {
if (err) reject(err)
else {
resolve(event)
}
})
}
}
})
},
(error) => {
reject(new ServiceUnavailableError(error))
}
)
})
}
const mutation = {
registerToEvent: {
type: EventType,
args,
resolve
}
}
export default mutation
@@ -0,0 +1,57 @@
import {
GraphQLNonNull,
GraphQLID,
GraphQLInt
} from 'graphql'
import { AuthentificationError, DatabaseError } from '../../errors'
import { isBetween } from '../../utils/functions'
import { EventType } from '../types'
import { Event } from '../../models'
const args = {
eventDesignator: { type: new GraphQLNonNull(GraphQLID) },
fromPosition: { type: new GraphQLNonNull(GraphQLInt) },
toPosition: { type: new GraphQLNonNull(GraphQLInt) }
}
const resolve = (parent, { eventDesignator, fromPosition, toPosition }, context) => {
const hostId = context.userId
if (!hostId) {
throw new AuthentificationError()
}
return new Promise((resolve, reject) => {
Event.findOne({ designator: eventDesignator, hostId: context.userId }).exec((err, event) => {
if (err) {
reject(err)
} else if (!event) {
reject(new DatabaseError('None of the events you own respond to that designator'))
} else {
const delta = fromPosition > toPosition ? 1 : -1
event.rules.forEach((part) => {
if (part.position === fromPosition) {
part.position = toPosition
} else if (isBetween(part.position, fromPosition, toPosition)) {
part.position += delta
}
})
event.save((err) => {
if (err) reject(err)
else {
resolve(event)
}
})
}
})
})
}
const mutation = {
reorderRules: {
type: EventType,
args,
resolve
}
}
export default mutation
+38
View File
@@ -0,0 +1,38 @@
import {
GraphQLObjectType
} from 'graphql'
import HostEventMutation from './HostEvent'
import EditEventMutation from './EditEvent'
import RegisterToEventMutation from './RegisterToEvent'
import EditParticipantMutation from './EditParticipant'
import AddRuleMutation from './AddRule'
import EditRuleMutation from './EditRule'
import ReorderRulesMutation from './ReorderRules'
import AddPrizeMutation from './AddPrize'
import EditPrizeMutation from './EditPrize'
import CreateFormulaMutation from './CreateFormula'
import CreateAndSetFormulaMutation from './CreateAndSetFormula'
import CreatePlotterMutation from './CreatePlotter'
import CreateAndSetPlotterMutation from './CreateAndSetPlotter'
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: Object.assign(
HostEventMutation,
EditEventMutation,
RegisterToEventMutation,
EditParticipantMutation,
AddRuleMutation,
EditRuleMutation,
ReorderRulesMutation,
AddPrizeMutation,
EditPrizeMutation,
CreateFormulaMutation,
CreateAndSetFormulaMutation,
CreatePlotterMutation,
CreateAndSetPlotterMutation
)
})
export default Mutation
+35
View File
@@ -0,0 +1,35 @@
import {
GraphQLInt,
GraphQLList
} from 'graphql'
import { EventType } from '../types'
import { Event } from '../../models'
const args = {
minDate: { type: GraphQLInt },
maxDate: { type: GraphQLInt }
}
const resolve = (parent, { minDate, maxDate }, context) => {
return Event.find(
Object.assign(
minDate || maxDate
? { startDatetime:
Object.assign(
minDate ? { $gte: minDate } : {},
maxDate ? { $lte: maxDate } : {}
) }
: {}
)
)
}
const query = {
events: {
type: new GraphQLList(EventType),
args,
resolve
}
}
export default query
+38
View File
@@ -0,0 +1,38 @@
import {
GraphQLInt,
GraphQLList,
GraphQLString
} from 'graphql'
import { EventType } from '../types'
import { Event } from '../../models'
const args = {
hostId: { type: GraphQLString },
minDate: { type: GraphQLInt },
maxDate: { type: GraphQLInt }
}
const resolve = (parent, { hostId, minDate, maxDate }, context) => {
return Event.find(
Object.assign(
hostId ? { hostId } : { hostId: context.userId },
minDate || maxDate
? { startDatetime:
Object.assign(
minDate ? { $gte: minDate } : {},
maxDate ? { $lte: maxDate } : {}
) }
: {}
)
)
}
const query = {
eventsByHost: {
type: new GraphQLList(EventType),
args,
resolve
}
}
export default query
+39
View File
@@ -0,0 +1,39 @@
import {
GraphQLInt,
GraphQLList,
GraphQLString,
GraphQLNonNull
} from 'graphql'
import { EventType } from '../types'
import { Event } from '../../models'
const args = {
teamId: { type: new GraphQLNonNull(GraphQLString) },
minDate: { type: GraphQLInt },
maxDate: { type: GraphQLInt }
}
const resolve = (parent, { teamId, minDate, maxDate }, context) => {
return Event.find(
Object.assign(
{ participants: { $elemMatch: { teamId } } },
minDate || maxDate
? { startDatetime:
Object.assign(
minDate ? { $gte: minDate } : {},
maxDate ? { $lte: maxDate } : {}
) }
: {}
)
)
}
const query = {
eventsByTeam: {
type: new GraphQLList(EventType),
args,
resolve
}
}
export default query
+21
View File
@@ -0,0 +1,21 @@
import {
GraphQLList
} from 'graphql'
import { FormulaType } from '../types'
import { Formula } from '../../models'
const args = {}
const resolve = (parent, args, context) => {
return Formula.find()
}
const query = {
formulas: {
type: new GraphQLList(FormulaType),
args,
resolve
}
}
export default query
+21
View File
@@ -0,0 +1,21 @@
import {
GraphQLList
} from 'graphql'
import { PlotterType } from '../types'
import { Plotter } from '../../models'
const args = {}
const resolve = (parent, args, context) => {
return Plotter.find()
}
const query = {
plotters: {
type: new GraphQLList(PlotterType),
args,
resolve
}
}
export default query
+22
View File
@@ -0,0 +1,22 @@
import {
GraphQLObjectType
} from 'graphql'
import EventsQuery from './Events'
import EventsByHostQuery from './EventsByHost'
import EventsByTeamQuery from './EventsByTeam'
import FormulasQuery from './Formulas'
import PlottersQuery from './Plotters'
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: Object.assign(
EventsQuery,
EventsByHostQuery,
EventsByTeamQuery,
FormulasQuery,
PlottersQuery
)
})
export default RootQuery
@@ -0,0 +1,16 @@
import {
GraphQLObjectType,
GraphQLString,
GraphQLInt
} from 'graphql'
const AdditionalPrizeType = new GraphQLObjectType({
name: 'OtherPrize',
fields: () => ({
condition: { type: GraphQLString },
amount: { type: GraphQLInt },
asset: { type: GraphQLString }
})
})
export default AdditionalPrizeType
+58
View File
@@ -0,0 +1,58 @@
import {
GraphQLObjectType,
GraphQLInt,
GraphQLString,
GraphQLList,
GraphQLID
} from 'graphql'
import {
FormulaType,
PlotterType,
RuleType,
ParticipantType,
PrizeType
} from './index'
const EventType = new GraphQLObjectType({
name: 'Event',
fields: () => ({
designator: { type: GraphQLID },
name: { type: GraphQLString },
hostId: { type: GraphQLString },
description: { type: GraphQLString },
startDatetime: { type: GraphQLInt },
finishDatetime: { type: GraphQLInt },
formula: {
type: FormulaType,
resolve (parent, args) {
return parent.formula
}
},
plotter: {
type: PlotterType,
resolve (parent, args) {
return parent.plotter
}
},
rules: {
type: new GraphQLList(RuleType),
resolve (parent, args) {
return parent.rules
}
},
participants: {
type: new GraphQLList(ParticipantType),
resolve (parent, args) {
return parent.participants
}
},
prizes: {
type: new GraphQLList(PrizeType),
resolve (parent, args) {
return parent.prizes
}
}
})
})
export default EventType
+17
View File
@@ -0,0 +1,17 @@
import {
GraphQLObjectType,
GraphQLString,
GraphQLBoolean
} from 'graphql'
const FormulaType = new GraphQLObjectType({
name: 'Formula',
fields: () => ({
id: { type: GraphQLString },
ownerId: { type: GraphQLString },
isTemplate: { type: GraphQLBoolean },
name: { type: GraphQLString }
})
})
export default FormulaType
+15
View File
@@ -0,0 +1,15 @@
import {
GraphQLObjectType,
GraphQLString
} from 'graphql'
const ParticipantType = new GraphQLObjectType({
name: 'Participant',
fields: () => ({
teamId: { type: GraphQLString },
botId: { type: GraphQLString },
releaseId: { type: GraphQLString }
})
})
export default ParticipantType
+20
View File
@@ -0,0 +1,20 @@
import {
GraphQLObjectType,
GraphQLString,
GraphQLBoolean
} from 'graphql'
const PlotterType = new GraphQLObjectType({
name: 'Plotter',
fields: () => ({
id: { type: GraphQLString },
ownerId: { type: GraphQLString },
isTemplate: { type: GraphQLBoolean },
name: { type: GraphQLString },
host: { type: GraphQLString },
repo: { type: GraphQLString },
moduleName: { type: GraphQLString }
})
})
export default PlotterType
+22
View File
@@ -0,0 +1,22 @@
import {
GraphQLObjectType,
GraphQLList,
GraphQLInt
} from 'graphql'
import { AdditionalPrizeType } from './index'
const PrizeType = new GraphQLObjectType({
name: 'Prize',
fields: () => ({
rank: { type: GraphQLInt },
amount: { type: GraphQLInt },
additional: {
type: new GraphQLList(AdditionalPrizeType),
resolve (parent, args) {
return parent.additional
}
}
})
})
export default PrizeType
+16
View File
@@ -0,0 +1,16 @@
import {
GraphQLObjectType,
GraphQLInt,
GraphQLString
} from 'graphql'
const RuleType = new GraphQLObjectType({
name: 'Rule',
fields: () => ({
position: { type: GraphQLInt },
title: { type: GraphQLString },
description: { type: GraphQLString }
})
})
export default RuleType
+17
View File
@@ -0,0 +1,17 @@
import PlotterType from './Plotter'
import RuleType from './Rule'
import ParticipantType from './Participant'
import AdditionalPrizeType from './AdditionalPrize'
import PrizeType from './Prize'
import FormulaType from './Formula'
import EventType from './Event'
export {
PlotterType,
RuleType,
ParticipantType,
AdditionalPrizeType,
PrizeType,
FormulaType,
EventType
}
+26
View File
@@ -0,0 +1,26 @@
export const capitalize = (string) => {
return (string).charAt(0).toUpperCase() + (string).slice(1)
}
export const slugify = (text) => {
return text.toString().toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w\-]+/g, '')
.replace(/\-\-+/g, '-')
.replace(/^-+/, '')
.replace(/-+$/, '')
}
export const epoch = () => {
return 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
} else {
return false
}
}