-
Notifications
You must be signed in to change notification settings - Fork 8
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
significantotter
wants to merge
4
commits into
wanderers-guide:main
Choose a base branch
from
significantotter:api-v2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Api v2 #14
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
9f0f4bd
initial commit with working barebones v2 api. Currently insecure and …
significantotter 6cec11b
fixes a typo and an issue with the findByName schema
significantotter efd75d6
fixes tsconfig issue, removes unused import
significantotter 225ac83
Adds 'not found' errors to the API
significantotter File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,6 +2,7 @@ node_modules | |
dist | ||
.jshintrc | ||
.env | ||
dev.env | ||
app.yaml | ||
TO-DO.txt | ||
redis-server.exe | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: { | ||
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}, | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()), | ||
}; | ||
}); | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", | ||
}, | ||
}, | ||
}, | ||
}, | ||
}; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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})} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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