Newer
Older
Labyrinth / src / LabyrinthMiddleware.ts
import * as graphqlHTTP from "express-graphql";
import {buildSchema} from "graphql";
import { GameServer } from "./GameServer";
import { Direction, MazeTile } from "./MazeMap";

export const schemaDefinition = `
    enum Direction {
        none
        top
        left
        bottom
        right
    }

    """
    Representing a tile with it's possible pathways.
    """
    type MazeTileQL {
        id: String!
        paths: [Direction!]!
    }

    type Mutation {
        "Start a new game"
        startGame(userID: String!, mapID: String!): MazeTileQL
    }

    type Query {
        "Tells you your where you currently are and how it looks there in case you forgot."
        currentPostition(userID: String!): MazeTileQL

        "Lists currently available maps."
        listMaps: [String!]!
    }
`;

class MazeTileQL
{
    public static DirectionToString(dir:Direction): string
    {
        switch (dir) {
            case Direction.none: return "none";
            case Direction.top: return "top";
            case Direction.left: return "left";
            case Direction.bottom: return "bottom";
            case Direction.right: return "right";
        }
    }

    public id:string;
    public paths:string[];

    constructor(tile:MazeTile)
    {
        this.id = tile.id;
        this.paths = tile.paths.map(MazeTileQL.DirectionToString);
    }
}

function createGraphQLRoot(games:GameServer)
{
    return {
        currentPostition: ({userID}) => new MazeTileQL(games.currentPosition(userID)),
        listMaps: () => games.listMaps(),
        startGame: ({userID, mapID}) => new MazeTileQL(games.startGame(userID, mapID)),
    };
}

export function CreateLabyrinthMiddleware(graphiql:boolean, games:GameServer): graphqlHTTP.Middleware
{
    const schema = buildSchema(schemaDefinition);

    const root = createGraphQLRoot(games);

    return graphqlHTTP({
        graphiql: true,
        rootValue: root,
        schema,
    });
}