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

Support new schema endpoint and metadata operations #13

Merged
merged 8 commits into from
Nov 16, 2023
Merged
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
30 changes: 29 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,31 @@
# Glide Tables Client

## Usage
## Authorization

Set `GLIDE_TOKEN` environment variable or pass the token as props.

## Apps

```ts
import * as glide from "@glideapps/tables";

// Create a reference to an app using its ID
const myApp = glide.app("bAFxpGXU1bHiBgUMcDgn");

// Or get by name
const myApp = await glide.getAppNamed("Employee Directory");

// Get all tables
const tables = await myApp.getTables();

// Get a table by name
const users = await myApp.getTableNamed("Users");

// List all apps
const apps = await glide.getApps();
```

## Tables

```ts
import * as glide from "@glideapps/tables";
Expand Down Expand Up @@ -42,6 +67,9 @@ await inventory.setRow(rowID, {

// Delete a row
await inventory.deleteRow(rowID);

// Get table schema info (columns and their types)
const schema = await inventory.getSchema();
Copy link

Choose a reason for hiding this comment

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

This doesn't make it clear to me that it's actually fetching the schema from Glide. Earlier in this sample, inventory is created by specifying the columns and their types, so I'd assume this would just return that again:

  columns: {
    Item: "string",
    Description: "string",
    Price: "number",

    // Handle internal column names != display names
    Assignee: { type: "string", name: "7E42F8B3-9988-436E-84D2-5B3B0B22B21F" },
  },`

I'm assuming that is still needed to get strongly typed rows? Might be good just to clarify the relationship between these

```

### Staging
Expand Down
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"@swc/core": "^1.3.44",
"@swc/jest": "^0.2.24",
"@types/jest": "^29.5.0",
"dotenv": "^16.3.1",
"jest": "^29.5.0",
"prettier": "^2.8.7",
"semver": "^7.3.8",
Expand Down
93 changes: 89 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { Client, makeClient } from "./rest";
import type { TableProps, Row, ColumnSchema, RowID, FullRow, AppProps } from "./types";

import fetch from "cross-fetch";

type RowIdentifiable<T extends ColumnSchema> = RowID | FullRow<T>;

type IDName = { id: string; name: string };

function rowID(row: RowIdentifiable<any>): RowID {
return typeof row === "string" ? row : row.$rowID;
}
Expand All @@ -18,19 +21,32 @@ const defaultEndpoint = "https://api.glideapp.io/api/function";
class Table<T extends ColumnSchema> {
private props: TableProps<T>;

private client: Client;

public get app(): string {
return this.props.app;
}

public get id(): string {
return this.props.table;
}

public get table(): string {
return this.props.table;
}

public get name() {
return this.props.name;
}

constructor(props: TableProps<T>) {
this.props = {
token: process.env.GLIDE_TOKEN,
...props,
token: props.token ?? process.env.GLIDE_TOKEN,
};
this.client = makeClient({
token: process.env.GLIDE_TOKEN!,
Copy link

Choose a reason for hiding this comment

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

Shouldn't this just be this.props.token now?

Suggested change
token: process.env.GLIDE_TOKEN!,
token: this.props.token!,

});
}

private renameOutgoing(rows: Row<T>[]): Row<T>[] {
Expand Down Expand Up @@ -159,6 +175,20 @@ class Table<T extends ColumnSchema> {
await this.deleteRows([row]);
}

public async getSchema(): Promise<{
data: { columns: Array<{ id: string; name: string; type: { kind: string } }> };
}> {
const { app, table } = this.props;

const response = await this.client.get(`/apps/${app}/tables/${table}/schema`);

if (response.status !== 200) {
throw new Error(`Failed to get schema: ${response.status} ${response.statusText}`);
}

return await response.json();
}

public async getRows(): Promise<FullRow<T>[]> {
const { token, app, table } = this.props;

Expand All @@ -175,7 +205,12 @@ class Table<T extends ColumnSchema> {
});

if (!response.ok) {
throw new Error(`Failed to get rows: ${response.status} ${response.statusText}`);
throw new Error(
`Failed to get rows: ${response.status} ${response.statusText} ${JSON.stringify({
app,
table,
})}`
);
}

const [result] = await response.json();
Expand All @@ -189,7 +224,38 @@ class Table<T extends ColumnSchema> {
}

class App {
constructor(private props: AppProps) {}
private props: AppProps;
private client: Client;

public get id() {
return this.props.id;
}

public get name() {
return this.props.name;
}

constructor(props: AppProps) {
this.props = { ...props, token: props.token ?? process.env.GLIDE_TOKEN! };
this.client = makeClient({
token: process.env.GLIDE_TOKEN!,
Copy link

Choose a reason for hiding this comment

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

Same again?

Suggested change
token: process.env.GLIDE_TOKEN!,
token: this.props.token!,

});
}

public async getTableNamed(name: string) {
const tables = await this.getTables();
return tables?.find(t => t.name === name);
}

public async getTables() {
const { id } = this.props;
const result = await this.client.get(`/apps/${id}/tables`);

if (result.status !== 200) return undefined;

const { data: tables }: { data: IDName[] } = await result.json();
return tables.map(t => this.table({ table: t.id, name: t.name, columns: {} }));
}

public table<T extends ColumnSchema>(props: Omit<TableProps<T>, "app">) {
return new Table<T>({
Expand All @@ -201,10 +267,29 @@ class App {
}
}

export function app(props: AppProps): App {
export function app(props: AppProps | string): App {
if (typeof props === "string") {
props = { id: props };
}
return new App(props);
}

export async function getApps(props: { token?: string } = {}): Promise<App[] | undefined> {
const client = makeClient(props);
const response = await client.get(`/apps`);
if (response.status !== 200) return undefined;
const { data: apps }: { data: IDName[] } = await response.json();
return apps.map(idName => app({ ...props, ...idName }));
}

export async function getAppNamed(
name: string,
props: { token?: string } = {}
): Promise<App | undefined> {
const apps = await getApps(props);
return apps?.find(a => a.name === name);
}

export function table<T extends ColumnSchema>(props: TableProps<T>) {
return new Table<T>(props);
}
20 changes: 20 additions & 0 deletions src/rest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import fetch from "cross-fetch";

export function makeClient({ token = process.env.GLIDE_TOKEN! }: { token?: string } = {}) {
return {
get(route: string, r: RequestInit = {}) {
return fetch(`https://functions.prod.internal.glideapps.com/api${route}`, {
Copy link

Choose a reason for hiding this comment

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

I feel like we're sort of committing to this endpoint, at least for some period of time, by shipping it here.. Just making sure we're cool with that /cc @timwellswa

Copy link
Member Author

Choose a reason for hiding this comment

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

I am prepared to change it. We will need to coordinate when we do, yes.

method: "GET",
...r,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
Accept: "application/json",
...r.headers,
},
});
},
};
}

export type Client = ReturnType<typeof makeClient>;
37 changes: 36 additions & 1 deletion src/table.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
require("dotenv").config();

import * as glide from ".";
import type { RowOf } from ".";

const token = process.env.GLIDE_TOKEN!;

const app = glide.app({
id: "bAFxpGXU1bHiBgUMcDgn",
token: process.env.GLIDE_TOKEN,
token,
});

const inventory = app.table({
Expand All @@ -25,6 +29,30 @@ const inventoryStaging = glide.table({
},
});

describe("app", () => {
it("can get apps", async () => {
const apps = await glide.getApps();
expect(apps).toBeDefined();
expect(apps?.length).toBeGreaterThan(0);
});

it("can get an app by name", async () => {
const app = await glide.getAppNamed("API Testing");
expect(app).toBeDefined();
});

it("can get tables", async () => {
const tables = await app.getTables();
expect(tables).toBeDefined();
expect(tables?.length).toBeGreaterThan(0);
});

it("can get a table by name", async () => {
const table = await app.getTableNamed("Inv - Inventory");
expect(table).toBeDefined();
});
});

describe("table", () => {
jest.setTimeout(60_000);

Expand Down Expand Up @@ -101,4 +129,11 @@ describe("table", () => {
const renamed = await inventory.getRow(rowID);
expect(renamed?.Item).toBe("Renamed");
});

it("can get schema", async () => {
const {
data: { columns },
} = await inventory.getSchema();
expect(columns).toBeTruthy();
});
});
4 changes: 3 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,10 @@ export type FullRow<T extends ColumnSchema> = Pretty<
} & Row<T>
>;

export interface TableProps<T> {
export interface TableProps<T = {}> {
token?: string;
endpoint?: string;
name?: string;

app: string;
table: string;
Expand All @@ -60,4 +61,5 @@ export interface AppProps {
id: string;
token?: string;
endpoint?: string;
name?: string;
}
Loading