Skip to content

Commit

Permalink
examples, parse param in httpraw, fix put
Browse files Browse the repository at this point in the history
  • Loading branch information
insyri committed Oct 17, 2022
1 parent dcd98dd commit c20e490
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 15 deletions.
74 changes: 65 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ ws.on('error', (_) => _);
ws.on<[string, string, number]>(
'message',
({ data }) =>
console.log(`${data[0]} said "${data[1]}" and sent ${data[2]} attachments`),
console.log(`${data[0]} said "${data[1]}" and sent ${data[2]} attachment(s).`),
);

// Remember this!
Expand All @@ -79,20 +79,76 @@ discord.on('MESSAGE_CREATE', async (message) => {
});
```

<!--
#### Get a guild's statistics.

const client = new Tpy(Deno.env.get('PYLON_TOKEN')!);
const guildStats = await client.getGuildStats('759174794968301569');
```ts
const client = new Tpy('PYLON_TOKEN');
const guildStats = await client.getGuildStats('GUILD_ID');
const mostRecent = guildStats.find((e) =>
e.date === Math.min(...guildStats.map((e) => e.date))
)!;
const { date, events, executionMsAvg } = mostRecent;

const mostRecentDateFormatted = new Date(date * 1000).toDateString();
console.log(
`On ${mostRecentDateFormatted}, there was a total of ${events} events with an average execution time of ${executionMsAvg} (in ms).`,
);
```

#### Get a deployment's listening events and cron tasks.

```ts
const client = new Tpy('PYLON_TOKEN');
const { config } = await client.getDeploymentfromGuild('GUILD_ID');
const { cronTasks } = config.tasks;
const { events } = config;
const cronTasksFormatted = cronTasks.map(({ cronString, name }) =>
` ${name} (${cronString})`
);

console.log(
`Listening to ${events.length} discord event(s):
${events.join(', ')}\n`,
`Running ${cronTasks.length} cron job(s):\n${cronTasksFormatted.join('\n')}`,
);
```

#### Get the keys in a KV namespace.

```ts
const client = new Tpy('PYLON_TOKEN');
const kvnamespace = 'tags';
const kv = client.KV(
kvnamespace,
(await client.getDeploymentfromGuild('GUILD_ID')).id,
);
if (!mostRecent) throw '???';
const mostRecentDateFormatted = new Date(mostRecent.date).getMilliseconds();
console.log(mostRecentDateFormatted);

-->
const keys = await kv.list({ limit: 10 });
const amountOfKeys = await kv.count();

console.log(
`There are ${amountOfKeys} key(s) within the ${kvnamespace} KV namespace, these are the first 10 (or less).
${keys.join(', ')}`,
);
```

<!-- TODO: add more examples; ws, kv, post deployment, other get stuff -->
#### Get and modify values within a KV namespace.

```ts
const client = new Tpy('PYLON_TOKEN');
const kvnamespace = 'tags';
const kv = client.KV(
kvnamespace,
(await client.getDeploymentfromGuild('GUILD_ID')).id,
);

const key = 'cool';
console.log(`Value of key "${key}":`, await kv.get(key));
await kv.put(key, 'rust');
console.log(`Value of key "${key}":`, await kv.get(key));
await kv.delete(key);
console.log(`Value of key "${key}":`, await kv.get(key));
```

## Contributing

Expand Down
2 changes: 2 additions & 0 deletions TODO
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
do mod.ts again
examples
11 changes: 9 additions & 2 deletions src/kv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,12 @@ export default class TpyKV {
new Context({ deploymentID }),
`/deployments/${deploymentID}/kv/namespaces/${kvnamespace}/items/${key}`,
'PUT',
{ body: JSON.stringify({ 'string': value }) },
{
body: JSON.stringify({
'string': typeof value === 'string' ? `"${value}"` : value,
}),
},
false,
);
}

Expand Down Expand Up @@ -125,7 +130,9 @@ export default class TpyKV {
response,
);
}
item = JSON.parse(p.value.string);
item = ['\'', '"', '`'].includes(p.value.string[0])
? JSON.parse(p.value.string)
: p.value.string;
break;
}
return item;
Expand Down
13 changes: 9 additions & 4 deletions src/tpy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,22 +263,27 @@ export default class Tpy {
*
* @param resource The resource to request that will be concatenated with the API URL.
* @param method HTTP method to use. Currently, the Pylon API only uses GET and POST.
* @param other Other fetch parameters.
* @param requestInit Other fetch parameters.
* @param parse Whether to parse out the body or not, default is true.
*
* @throws {TpyError<Response | Context>}
*/
async httpRaw<T>(
ctx: Context,
resource: `/${string}`,
method: Pylon.HTTPVerbs = 'GET',
other: RequestInit = {},
requestInit: RequestInit = {},
parse = true,
): Promise<T> {
const response = await fetch(
'https://pylon.bot/api' + resource,
this.readyRequest(method, other),
this.readyRequest(method, requestInit),
);

if (response.ok) return await response.json() as T;
if (response.ok) {
if (parse) return await response.json() as T;
return {} as T;
}

switch (response.status) {
case 404: {
Expand Down

0 comments on commit c20e490

Please sign in to comment.