Skip to content

Commit

Permalink
' -> " and fixes #16
Browse files Browse the repository at this point in the history
  • Loading branch information
insyri committed Dec 3, 2022
1 parent ac0ee89 commit 19b8e53
Show file tree
Hide file tree
Showing 13 changed files with 171 additions and 170 deletions.
34 changes: 17 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ download the type dependencies locally.
#### Get the token's matching user.

```ts
const client = new Tpy({ token: 'PYLON_TOKEN' });
const client = new Tpy({ token: "PYLON_TOKEN" });
const { displayName, id } = await client.getUser();

console.log(`Logged in as ${displayName} (<@${id}>).`);
Expand Down Expand Up @@ -69,7 +69,7 @@ await ws.connect();
With the following Pylon code:

```ts
discord.on('MESSAGE_CREATE', async (message) => {
discord.on("MESSAGE_CREATE", async (message) => {
console.log(
// string
message.author.username,
Expand All @@ -84,8 +84,8 @@ discord.on('MESSAGE_CREATE', async (message) => {
#### Get a guild's statistics.

```ts
const client = new Tpy({ token: 'PYLON_TOKEN' });
const guildStats = await client.getGuildStats('GUILD_ID');
const client = new Tpy({ token: "PYLON_TOKEN" });
const guildStats = await client.getGuildStats("GUILD_ID");
const mostRecent = guildStats.find((e) =>
e.date === Math.min(...guildStats.map((e) => e.date))
)!;
Expand All @@ -101,8 +101,8 @@ console.log(

```ts
const client = new Tpy({
token: 'PYLON_TOKEN',
deploymentID: 'DEPLOYMENT_ID',
token: "PYLON_TOKEN",
deploymentID: "DEPLOYMENT_ID",
});
const { config } = await client.getDeployment();
const { cronTasks } = config.tasks;
Expand All @@ -113,45 +113,45 @@ const cronTasksFormatted = cronTasks.map(({ cronString, name }) =>

console.log(
`Listening to ${events.length} discord event(s):
${events.join(', ')}\n`,
`Running ${cronTasks.length} cron job(s):\n${cronTasksFormatted.join('\n')}`,
${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({ token: 'PYLON_TOKEN' });
const kvnamespace = 'tags';
const client = new Tpy({ token: "PYLON_TOKEN" });
const kvnamespace = "tags";
const kv = client.KV(
kvnamespace,
await client.getDeploymentIDfromGuild('GUILD_ID'),
await client.getDeploymentIDfromGuild("GUILD_ID"),
);

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(', ')}`,
${keys.join(", ")}`,
);
```

#### Get and modify values within a KV namespace.

```ts
const client = new Tpy({ token: 'PYLON_TOKEN' });
const kvnamespace = 'NAMESPACE';
const client = new Tpy({ token: "PYLON_TOKEN" });
const kvnamespace = "NAMESPACE";
const kv = client.KV(
kvnamespace,
await client.getDeploymentIDfromGuild('GUILD_ID'),
await client.getDeploymentIDfromGuild("GUILD_ID"),
);

const key = 'cool_lang';
const key = "cool_lang";

console.log(`Value of key "${key}":`, await kv.get(key));

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

await kv.delete(key);
Expand Down
2 changes: 1 addition & 1 deletion deno.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
},
"fmt": {
"options": {
"singleQuote": true,
"singleQuote": false,
"useTabs": false,
"indentWidth": 2,
"lineWidth": 80
Expand Down
20 changes: 10 additions & 10 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,17 +60,17 @@

// Used for docs.
// deno-lint-ignore no-unused-vars
import { type Tpy } from './src/tpy.ts';
import { type Tpy } from "./src/tpy.ts";

export { Tpy as default } from './src/tpy.ts';
export { TpyWs } from './src/ws.ts';
export { TpyKV } from './src/kv.ts';
export { TpyError, TpyErrors } from './src/error.ts';
export { Context } from './src/context.ts';
export { Tpy as default } from "./src/tpy.ts";
export { TpyWs } from "./src/ws.ts";
export { TpyKV } from "./src/kv.ts";
export { TpyError, TpyErrors } from "./src/error.ts";
export { Context } from "./src/context.ts";

import type * as Guild from './src/types/guild.d.ts';
import type * as Deployment from './src/types/deployment.d.ts';
import type * as User from './src/types/user.d.ts';
import type * as Pylon from './src/types/pylon.d.ts';
import type * as Guild from "./src/types/guild.d.ts";
import type * as Deployment from "./src/types/deployment.d.ts";
import type * as User from "./src/types/user.d.ts";
import type * as Pylon from "./src/types/pylon.d.ts";

export type { Deployment, Guild, Pylon, User };
3 changes: 2 additions & 1 deletion node-transform.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ $Destination = "node"
$NodePackageLocation = "$Destination/package.json"
$ImportRegex = "(?<=(?<=\n|^)(im|ex)port(?:(?!(\.d)?\.ts).|\n)*)(\.d)?\.ts"
$NodeOnlyRegex = "\/\/ build:node-only "
$DiscordAPIRegex = "(?<=discord-api-types\/[a-z]+\/v8)\/guild"

[string[]]$PresentFiles = @()
$ItemList + $DeleteList | ForEach-Object {
Expand Down Expand Up @@ -61,7 +62,7 @@ If ($Version) {
# Node Import Syntax Fix
Get-ChildItem $Destination -Recurse -Filter *.ts | ForEach-Object {
$Content = Get-Content $_.FullName -Raw
$Content -replace "($ImportRegex|$NodeOnlyRegex)", "" > $_.FullName
$Content -replace "($ImportRegex|$NodeOnlyRegex|$DiscordAPIRegex)", "" > $_.FullName
}

# Verification
Expand Down
4 changes: 2 additions & 2 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,11 @@ export class Context {
/**
* A null context number.
*/
static nullNumber = '-1';
static nullNumber = "-1";
/**
* A null context string.
*/
static nullString = '<null string>';
static nullString = "<null string>";

/**
* Whether the given context matches a nullish context value.
Expand Down
46 changes: 23 additions & 23 deletions src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export interface ITpyErrorsProperty {
* @template T The type of {@linkcode rawInfo}.
*/
export class TpyError<T> extends Error
implements Omit<ITpyErrorsProperty, 'message'> {
implements Omit<ITpyErrorsProperty, "message"> {
/**
* A short description of the Tpy error.
*/
Expand Down Expand Up @@ -109,61 +109,61 @@ export class TpyError<T> extends Error
* defintion with specific context information.
*/
export const TpyErrors = {
'Internal Server Error': {
"Internal Server Error": {
message: (s: string) => serverRespondedWith(s),
description:
`Sometimes thrown when a request's authorization header is invalid.`,
},
'Missing or Unexpected Value in Response': {
"Missing or Unexpected Value in Response": {
message: (s: string) => `Response structure validation failed: ${s}.`,
description: 'Response structure is incomplete or has unexpected behavior.',
description: "Response structure is incomplete or has unexpected behavior.",
},
'Missing or Invalid JSON in Request Body': {
"Missing or Invalid JSON in Request Body": {
message: (s: string) =>
`With given field(s) ${s} were unsatisfactory; contains invalid JSON.`,
description:
`The fetch contents sent were did not have the required JSON body.`,
},
'Guild Not Found': {
message: (s: string) => couldNotBeFound('Guild ID', s),
"Guild Not Found": {
message: (s: string) => couldNotBeFound("Guild ID", s),
description: `The guild specified was not found.`,
},
'Deployment Not Found': {
message: (s: string) => couldNotBeFound('Deployment ID', s),
"Deployment Not Found": {
message: (s: string) => couldNotBeFound("Deployment ID", s),
description: `The deployment specified was not found.`,
},
'HTTP Method Not Allowed': {
"HTTP Method Not Allowed": {
message: (s: string) => serverRespondedWith(s),
description: 'The HTTP method is not allowed.',
description: "The HTTP method is not allowed.",
},
'Unidentifiable Error': {
"Unidentifiable Error": {
message: (s: string) =>
`Unidentifiable error caught, deterministic via fields: ${s}`,
description:
'The error was unidentifiable, see details with `<TpyError>.rawInfo`.',
"The error was unidentifiable, see details with `<TpyError>.rawInfo`.",
},
'URL Resource Not Found': {
"URL Resource Not Found": {
message: (s: string) => serverRespondedWith(s),
description: 'The URL resource on the web server was not found.',
description: "The URL resource on the web server was not found.",
},
Unauthorized: {
message: (s: string) => serverRespondedWith(s),
description: 'Required credentials were missing from the request.',
description: "Required credentials were missing from the request.",
},
Forbidden: {
message: (s: string) => serverRespondedWith(s),
description:
'Access to the resource is denied despite included credentials.',
"Access to the resource is denied despite included credentials.",
},
'Missing or Invalid Required Parameter': {
"Missing or Invalid Required Parameter": {
message: (s: string) =>
`Required parameter(s) ${s} were missing or invalid.`,
description: 'Required parameter(s) were missing or invalid.',
description: "Required parameter(s) were missing or invalid.",
},
'Nullish Context': {
"Nullish Context": {
message: (s: string) =>
`Context parameter ${s} is nullish, where access is necessary.`,
description: 'A context parameter was missing where it was needed.',
description: "A context parameter was missing where it was needed.",
},
};

Expand Down Expand Up @@ -194,11 +194,11 @@ export function responseBody(s: string) {
* @param params The parameter(s) in this context.
*/
export function parametersPrompt(
issue: 'missing' | 'incompatible',
issue: "missing" | "incompatible",
params: string | string[],
) {
return `Parameter(s) are ${issue}: ${
Array.isArray(params) ? params.join(', ') : params
Array.isArray(params) ? params.join(", ") : params
}`;
}

Expand Down
40 changes: 20 additions & 20 deletions src/kv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
* @module
*/

import { Tpy } from './tpy.ts';
import type { Json, KV } from './types/pylon.d.ts';
import { parametersPrompt, TpyError } from './error.ts';
import { Context } from './context.ts';
import { Tpy } from "./tpy.ts";
import type { Json, KV } from "./types/pylon.d.ts";
import { parametersPrompt, TpyError } from "./error.ts";
import { Context } from "./context.ts";

/**
* A KVNamespace interface that (almost) matches the Pylon KVNamespace SDK class.
Expand All @@ -31,20 +31,20 @@ export class TpyKV {
constructor(tpyInstance: Tpy, deploymentID: string, kvnamespace: string) {
if (!tpyInstance || !(tpyInstance instanceof Tpy)) {
throw new TpyError(
'Missing or Invalid Required Parameter',
"Missing or Invalid Required Parameter",
parametersPrompt(
!tpyInstance ? 'missing' : 'incompatible',
'tpyInstance',
!tpyInstance ? "missing" : "incompatible",
"tpyInstance",
),
'tpyInstance',
"tpyInstance",
tpyInstance,
);
}
if (!deploymentID) {
throw new TpyError(
'Missing or Invalid Required Parameter',
parametersPrompt('missing', 'deploymentID'),
'deploymentID',
"Missing or Invalid Required Parameter",
parametersPrompt("missing", "deploymentID"),
"deploymentID",
deploymentID,
);
}
Expand All @@ -66,10 +66,10 @@ export class TpyKV {
await this.tpyc.httpRaw(
new Context({ deploymentID }),
`/deployments/${deploymentID}/kv/namespaces/${kvnamespace}/items/${key}`,
'PUT',
"PUT",
{
body: JSON.stringify({
string: typeof value === 'string' ? `"${value}"` : value,
string: typeof value === "string" ? `"${value}"` : value,
}),
},
false,
Expand All @@ -93,7 +93,7 @@ export class TpyKV {
await this.tpyc.httpRaw(
new Context({ deploymentID, kvnamespace }),
`/deployments/${deploymentID}/kv/namespaces/${kvnamespace}/items/${key}`,
'PUT',
"PUT",
{ body: JSON.stringify({ bytes: value }) },
false,
);
Expand All @@ -117,13 +117,13 @@ export class TpyKV {
if (p.key !== key) continue;
if (!p.value.string) {
throw new TpyError(
'Missing or Unexpected Value in Response',
"Missing or Unexpected Value in Response",
`response[${i}].value.string is undefined`,
`response[${i}].value.string`,
response,
);
}
item = ['\'', '"', '`'].includes(p.value.string[0])
item = ["'", '"', "`"].includes(p.value.string[0])
? JSON.parse(p.value.string)
: p.value.string;
break;
Expand Down Expand Up @@ -210,10 +210,10 @@ export class TpyKV {
: i.value.bytes;
if (!j) {
throw new TpyError(
'Missing or Unexpected Value in Response',
"Missing or Unexpected Value in Response",
`response[${i}].value.string and/or response[${i}].value.bytes are undefined`,
[`response[${i}].value.string`, `response[${i}].value.bytes`].join(
', ',
", ",
),
response,
);
Expand Down Expand Up @@ -255,7 +255,7 @@ export class TpyKV {
await this.tpyc.httpRaw<KV.DELETE.Namespace>(
new Context({ deploymentID, kvnamespace }),
`/deployments/${deploymentID}/kv/namespaces/${kvnamespace}`,
'DELETE',
"DELETE",
)
).keys_deleted;
}
Expand All @@ -274,7 +274,7 @@ export class TpyKV {
await this.tpyc.httpRaw(
new Context({ deploymentID, kvnamespace }),
`/deployments/${deploymentID}/kv/namespaces/${kvnamespace}/items/${key}`,
'DELETE',
"DELETE",
{},
false,
);
Expand Down
Loading

0 comments on commit 19b8e53

Please sign in to comment.