Skip to content

Commit

Permalink
Initial commit (mvp)
Browse files Browse the repository at this point in the history
  • Loading branch information
juusaw committed Feb 14, 2019
0 parents commit c3bbfec
Show file tree
Hide file tree
Showing 4 changed files with 1,127 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
16 changes: 16 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "d20ql",
"version": "1.0.0",
"main": "index.js",
"author": "juusaw",
"license": "MIT",
"dependencies": {
"apollo-server": "^2.4.0",
"graphql": "^14.1.1",
"ts-node": "^8.0.2",
"typescript": "^3.3.3"
},
"scripts": {
"start": "ts-node src/index.ts"
}
}
57 changes: 57 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { ApolloServer } from 'apollo-server'
import { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLNonNull, GraphQLFloat } from 'graphql'

type Dice = [number, number, number]

function parseDice(dice: string): Dice {
const [multiplier, sides, constant] = dice
.match(/(\d*)d(\d+)([\+|-]\d+)?/)
.slice(1)
.map(str => parseInt(str, 10))
return [
multiplier || 1,
sides,
constant || 0
]
}

function countResult(multiplier: number, sides: number, constant: number) {
return multiplier * Math.floor(Math.random() * sides + 1) + constant
}

function calculateMean(multiplier: number, sides: number, constant: number) {
return multiplier * (sides + 1) / 2 + constant
}

const RollResultType = new GraphQLObjectType({
name: 'Roll',
fields: {
result: { type: GraphQLInt, resolve: (parent: {dice: Dice}) => countResult(...parent.dice) },
statistics: { type: GraphQLFloat, resolve: (parent: {dice: Dice}) => calculateMean(...parent.dice) }
}
})

const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
roll: {
type: RollResultType,
description: 'Roll a dice. Example argument: 2d12+5',
args: {
dice: {
name: 'dice',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (_, args) => ({dice: parseDice(args.dice)})
}
}
})
})

const server = new ApolloServer({ schema })

server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
})
Loading

0 comments on commit c3bbfec

Please sign in to comment.