Skip to content

Commit

Permalink
🎉 Big Bang
Browse files Browse the repository at this point in the history
  • Loading branch information
jcrqr committed Aug 15, 2021
0 parents commit d71d0f5
Show file tree
Hide file tree
Showing 10 changed files with 29,345 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.vscode
17 changes: 17 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Contributing Guide

Thank you for considering contributing to this repository!

Please note that by participating, you are expected to uphold the [Contributor Covenant Code of Conduct](CODE_OF_CONDUCT.md).

## Generating OpenAPI Types

**NOTE:** The generation is done by calling [`drwpow/openapi-typescript`](https://github.com/drwpow/openapi-typescript) through `npm exec` command.

```bash
$ deno run --allow-env --allow-run gen.ts
```

## Guidelines

* Please keep it safe for work.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2021 João Cerqueira and contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# :fallen_leaf: Octono

> GitHub REST API for Deno projects.
:construction: Under active development.

## Usage

```typescript
import { request } from "./mod.ts";

const { data: repos } = await request("GET /orgs/{org}/repos", {
org: "octocat"
})

for (const repo of repos) {
console.log(`Found repo: ${repo.full_name}`)
}
```

See [example.ts](example.ts). Use `deno run --allow-env --allow-net example.ts` to run it.

## Permissions

This module requires `--allow-env` and `--allow-net` permissions.

## Contributing

Please, see [CONTRIBUTING.md](CONTRIBUTING.md) to learn how you can contribute to this repository.

## License

This project is released under the [MIT License](/LICENSE).
5 changes: 5 additions & 0 deletions deps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// gen
export type {
operations as Operations,
paths as Endpoints,
} from "./gen/openapi.d.ts";
9 changes: 9 additions & 0 deletions example.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { request } from "./mod.ts";

const { data: repos } = await request("GET /users/{username}/repos", {
username: "octocat"
})

for (const repo of repos) {
console.log(`Found repo: ${repo.full_name} (${repo.stargazers_count} stars)`)
}
22 changes: 22 additions & 0 deletions gen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const OAS_VERSION = Deno.env.get("GITHUB_OAS_VERSION") || "v1.1.3"

const OAS_URL =
`https://raw.githubusercontent.com/github/rest-api-description/${OAS_VERSION}/descriptions/api.github.com/api.github.com.json`;

async function genOpenAPITypes(): Promise<boolean> {
const p = Deno.run({
cmd: [
"npx",
"openapi-typescript",
OAS_URL,
"--output",
"./gen/openapi.d.ts",
],
});

const status = await p.status();

return status.success;
}

genOpenAPITypes();
29,111 changes: 29,111 additions & 0 deletions gen/openapi.d.ts

Large diffs are not rendered by default.

125 changes: 125 additions & 0 deletions lib/octono.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { Endpoints } from "../deps.ts";

const GITHUB_URL = Deno.env.get("GITHUB_URL") || "https://api.github.com";

export type Endpoint = string & keyof Endpoints;

export type EndpointMethod<E extends Endpoint = Endpoint> = string &
keyof Endpoints[E];

export type EndpointParameters<
E extends Endpoint,
M extends EndpointMethod<E>
> = (Endpoints[E][M] extends { parameters: { path: Record<string, unknown> } }
? Endpoints[E][M]["parameters"]["path"]
: Record<string, unknown>) &
(Endpoints[E][M] extends { parameters: { query: Record<string, unknown> } }
? Endpoints[E][M]["parameters"]["query"]
: Record<string, unknown>);

export type EndpointResponses<
E extends Endpoint,
M extends EndpointMethod<E>
> = Endpoints[E][M] extends {
responses: { "200": { content: Record<string | number, unknown> } };
}
? // @ts-ignore FIXME: doesn't work if we add "application/json" to the extends check
Endpoints[E][M]["responses"]["200"]["content"]["application/json"]
: unknown;

export type EndpointPrefixed = Endpoint extends `${infer T}`
? T extends Endpoint
? `${Uppercase<EndpointMethod<T>>} ${T}`
: never
: never;

export type EndpointsMap = {
[E in EndpointPrefixed]: {
options: E extends `${infer M} ${infer E}`
? E extends Endpoint
? Lowercase<M> extends EndpointMethod<E>
? EndpointParameters<E, Lowercase<M>>
: undefined
: undefined
: undefined;
responses: E extends `${infer M} ${infer E}`
? E extends Endpoint
? Lowercase<M> extends EndpointMethod<E>
? EndpointResponses<E, Lowercase<M>>
: unknown
: unknown
: unknown;
};
};

export class OctonoResponse<T> extends Response {
public data: T;

constructor(body: T, resp: ResponseInit) {
super(body as unknown as Uint8Array, resp);

this.data = body;
}
}

export async function request<
E extends EndpointPrefixed = EndpointPrefixed,
O extends EndpointsMap[E]["options"] = EndpointsMap[E]["options"],
R extends EndpointsMap[E]["responses"] = EndpointsMap[E]["responses"]
>(
endpointPrefixed: E,
options?: O,
init?: RequestInit
): Promise<OctonoResponse<R>> {
const [method, endpoint, extraParams] = parseEndpoint(
endpointPrefixed,
options || {}
);

const url = new URL(endpoint, GITHUB_URL);

if (method === "GET") {
for (const [name, value] of Object.entries(extraParams)) {
url.searchParams.set(name, value);
}
}

const resp = await fetch(url, {
...init,
method,
body: method !== "GET" ? JSON.stringify(extraParams) : null,
});

return new OctonoResponse<R>(await resp.json(), resp);
}

function parseEndpoint(
str: string,
params: Record<string, unknown>
): [string, string, Record<string, string>] {
const [method, endpoint] = str.split(" ");

const pathParams = endpoint
.split("/")
.map((p) => (p.match(/{(.+)}/) || [])[1])
.filter((p) => !!p);

const extraParams = Object.entries(params)
.filter(([p]) => !pathParams.includes(p))
.reduce((m, [p, d]) => ({ ...m, [p]: d }), {});

const endpointWithParams = endpoint
.split("/")
.map((part) => {
const pathParam = pathParams.find((p) => part === `{${p}}`);

if (!pathParam) {
return part;
}

return part.replace(`{${pathParam}}`, params[pathParam] as string);
})
.join("/");

return [method, endpointWithParams, extraParams];
}
1 change: 1 addition & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./lib/octono.ts"

0 comments on commit d71d0f5

Please sign in to comment.