Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Api v2 #14

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ node_modules
dist
.jshintrc
.env
dev.env
app.yaml
TO-DO.txt
redis-server.exe
Expand Down
5 changes: 5 additions & 0 deletions api/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { PrismaClient } from "@prisma/client";
import dotenv from "dotenv";
dotenv.config();

export const prisma = new PrismaClient();
142 changes: 142 additions & 0 deletions api/controllerBuilder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import _ from "lodash";
import OpenAPIBackend, { Handler, Request } from "openapi-backend";
import { OpenAPIV3_1 } from "openapi-types";
import { prisma as prismaType } from "./config";
import { Controller } from "./util/abstract/controller";
import { Schema } from "./util/abstract/schema";
import { Service } from "./util/abstract/service";
import { parseableJsonSchema } from "./schema/parsableSchema.js";
import { FormatDefinition } from "ajv";

const securitySchemes: Record<
string,
OpenAPIV3_1.SecuritySchemeObject | OpenAPIV3_1.ReferenceObject
> = {
ApiKey: {
type: "apiKey",
name: "x-api-key",
in: "header",
},
Oauth2: {
type: "oauth2",
flows: {
authorizationCode: {
authorizationUrl: "foo",
tokenUrl: "bar",
refreshUrl: "baz",
scopes: {
["feat:write"]: "foo",
},
},
},
},
};

const apiSchema: OpenAPIV3_1.Document = {
openapi: "3.0.3",
info: {
title: "Wanderer's Guide API v2",
description:
"Welcome to the Wanderer's Guide API! The goal of this documentation is to empower and inform developers in the ways they can utilize the resources Wanderer's Guide provides.",
termsOfService: "https://wanderersguide.app/license",
contact: {
email: "[email protected]",
},
license: {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We may need to update this to ORC.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ORC isn't available yet unfortunately, but when it is we can look at updating this

name: "Open Game License 1.0",
url: "https://wanderersguide.app/license",
},
version: "0.1",
},
externalDocs: {
description: "Find out more about the legacy Wanderer's Guide API",
url: "https://wanderersguide.app/api_docs",
},
tags: [
{
name: "Feat",
description: "Pathfinder 2E Feats",
},
],
components: {
schemas: parseableJsonSchema,
securitySchemes: securitySchemes,
},
security: [{ ApiKey: [] }],
};

const schemaPath: OpenAPIV3_1.PathsObject = {
"/docs": {
get: {
operationId: "getV2ApiDocs",
summary: "Get V2 API Docs",
responses: {
200: {
description:
"Gets the OpenAPI V3 JSON spec for the v2 Wanderer's Guide API",
content: {
"application/json": {},
},
},
},
},
},
};
function createSchemaHandler(schema) {
return (context, req, res) => {
return res.status(200).json(schema);
};
}

const errorHandlers = {
validationFail: async (c, req: Request, res) =>
res.status(400).json({ err: c.validation.errors }),
notFound: async (c, req: Request, res) =>
res.status(404).json({ err: "not found" }),
};

export function createApi({
prisma,
resources,
}: {
prisma: typeof prismaType;
resources: {
service: Service<any>;
controller: Controller<any, any>;
schema: Schema<any>;
factory: any;
}[];
}) {
let paths: OpenAPIV3_1.PathsObject = { ...schemaPath };
let handlers: { [key: string]: Handler } = {};

for (const resource of resources) {
paths = _.merge(paths, resource.schema.exportSchemas());
handlers = _.merge(handlers, resource.controller.exportHandlers());
}

const schema = _.cloneDeep(apiSchema) as OpenAPIV3_1.Document;
schema.paths = paths;

handlers.getV2ApiDocs = createSchemaHandler(_.cloneDeep(schema));

const api = new OpenAPIBackend({
definition: schema,
handlers: { ...errorHandlers, ...handlers },

customizeAjv: (ajv, ajvOpts, validationContext) => {
let dtFormat: FormatDefinition<string> = {
type: "string",
async: false,
validate:
/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,
};
ajv.addFormat("date-time", dtFormat);
return ajv;
},
});

api.init();

return api;
}
38 changes: 38 additions & 0 deletions api/resources/feats/feat.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Context, Request } from "openapi-backend";
import { Controller } from "../../util/abstract/controller";
import { Feats } from "../resourceTypes";
import { FeatService } from "./feat.service";

export class FeatController extends Controller<Feats, FeatService> {
constructor({ service }: { service: InstanceType<typeof FeatService> }) {
super({ service, resourceName: "feats" });
}
public get methods() {
return ["get", "getById", "findByName", "create", "update", "delete"];
}

public async findByName(c: Context, req: Request, res): Promise<any> {
const name = c.request.query.name.toString();
const page = Number(c.request.query.page || 0);
const pageSize = Number(c.request.query.pageSize || 100);

const offset = page * pageSize;

const names = await this.service.findByName({
name,
offset,
count: pageSize,
});
const totalCount = await this.service.getTotalCount({
where: { name: { contains: name } },
});
return res.status(200).json({
data: names,
pagination: {
page,
pageSize,
totalCount,
},
});
}
}
75 changes: 75 additions & 0 deletions api/resources/feats/feat.factory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import {
feats,
feats_actions,
feats_rarity,
feats_genericType,
} from "@prisma/client";
import { prisma } from "../../config.js";
import { Factory } from "fishery";
import { faker } from "@faker-js/faker";

// maybe replace in the near future with https://github.com/json-schema-faker/json-schema-faker/tree/2962d4eaab84bc2d05d1cb6838c74b36fd9ef8ae/docs


function sometimesNull(val: any, chance = 0.05) {
return Math.random() < chance ? null : val;
}

export const FeatFactory = Factory.define<Omit<feats, "id">>(({ onCreate }) => {
onCreate((feat) => prisma.feats.create({ data: feat }));

const featsActions = faker.helpers.arrayElement([
"NONE",
"FREE_ACTION",
"REACTION",
"ACTION",
"TWO_ACTIONS",
"THREE_ACTIONS",
]) as feats_actions;

const featsRarity = faker.helpers.arrayElement([
"COMMON",
"UNCOMMON",
"RARE",
"UNIQUE",
]) as feats_rarity;

const featsGenericType = faker.helpers.arrayElement([
"GENERAL_FEAT",
"SKILL_FEAT",
"CLASS_FEAT",
"ARCHETYPE_FEAT",
"ANCESTRY_FEAT",
"BASIC_ACTION",
"SKILL_ACTION",
"CREATURE_ACTION",
"COMPANION_ACTION",
]) as feats_genericType;

return {
name: sometimesNull(faker.random.words()),
actions: sometimesNull(featsActions),
level: faker.datatype.number({ max: 20, min: 1 }),
rarity: featsRarity,
prerequisites: sometimesNull(faker.random.words()),
frequency: sometimesNull(faker.random.words()),
cost: sometimesNull(faker.random.words()),
trigger: sometimesNull(faker.random.words()),
requirements: sometimesNull(faker.random.words()),
description: sometimesNull(faker.random.words()),
special: sometimesNull(faker.random.words()),
canSelectMultiple: sometimesNull(Number(faker.datatype.boolean)),
isDefault: sometimesNull(Number(faker.datatype.boolean)),
skillID: sometimesNull(faker.random.numeric(3)),
minProf: sometimesNull(faker.random.words()),
code: sometimesNull(faker.random.words()),
isCore: sometimesNull(Number(faker.datatype.boolean)),
genericType: sometimesNull(featsGenericType),
genTypeName: sometimesNull(faker.random.words()),
isArchived: sometimesNull(Number(faker.datatype.boolean)),
contentSrc: sometimesNull(faker.random.words()),
homebrewID: sometimesNull(faker.random.numeric(3)),
version: sometimesNull(faker.random.words()),
};
});

50 changes: 50 additions & 0 deletions api/resources/feats/feat.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import _ from "lodash";
import { OpenAPIV3_1 } from "openapi-types";
import { Schema } from "../../util/abstract/schema";
import { Feats } from "../resourceTypes";

export class FeatSchema extends Schema<Feats> {
constructor() {
super({ resourceName: "feats" });
}
public get methods() {
return ["get", "getById", "findByName", "create", "update", "delete"];
}

findByName(): OpenAPIV3_1.PathsObject {
return {
"/feat/findByName": {
get: {
tags: ["feat"],
summary: "Fetches a page of feats filtered by name.",
operationId: "featsFindByName",
parameters: [
{
name: "name",
in: "query",
description: "the name to search for",
required: true,
schema: { type: "string" },
},
],
responses: {
200: {
description: "successful operation",
content: {
"application/json": {
schema: {
type: "array",
items: { $ref: "#/components/schemas/feats" },
},
},
},
},
400: {
description: "Invalid name value",
},
},
},
},
};
}
}
37 changes: 37 additions & 0 deletions api/resources/feats/feat.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Service } from "../../util/abstract/service.js";
import { Feats } from "../resourceTypes.js";
import { prisma as prismaType, } from "./../../config.js";

export class FeatService extends Service<Feats> {
prisma: typeof prismaType;
constructor({ prisma }: { prisma: typeof prismaType }) {
super({ prisma, resourceName: "feats" });
this.prisma = prisma;
}
public findByName({
name,
offset,
count,
}: {
name: string;
offset: number;
count: number;
}) {
return this.prisma.feats.findMany({
skip: offset,
take: count,
where: {
name: {
contains: name,
},
},
orderBy: {
id: "asc",
},
});
}
}

const foo = new FeatService({prisma:prismaType});
async ()=>{
const feat = await foo.getById({id:1})}
17 changes: 17 additions & 0 deletions api/resources/feats/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { FeatController } from "./feat.controller";
import { FeatFactory } from "./feat.factory";
import { FeatService } from "./feat.service";
import { FeatSchema } from "./feat.schema";

export function bootstrapFeats({ prisma }) {
const featSchema = new FeatSchema();
const featService = new FeatService({ prisma });
const featController = new FeatController({ service: featService });
const featFactory = FeatFactory;
return {
schema: featSchema,
service: featService,
controller: featController,
factory: featFactory,
};
}
11 changes: 11 additions & 0 deletions api/resources/resourceTypes.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Prisma } from "@prisma/client";

export type Feats = {
name: "feats";
createArgs: Prisma.featsCreateArgs;
updateArgs: Prisma.featsUpdateArgs;
countArgs: Prisma.featsCountArgs;

};

export type Resource = Feats; // | Character | otherResource etc.
Loading