Skip to content

Commit

Permalink
feat(managers): move managers to root of lib
Browse files Browse the repository at this point in the history
  • Loading branch information
pxseu committed Nov 1, 2021
1 parent 4dd8117 commit ffa4e2b
Show file tree
Hide file tree
Showing 4 changed files with 104 additions and 95 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Imperial } from "..";
import type { Imperial } from "../client";

export class Base {
constructor(client: Imperial) {
Expand Down
133 changes: 39 additions & 94 deletions src/lib/client/Managers/Document.ts → src/lib/managers/Document.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { Base } from "./Base";
import { NO_ID, NO_TEXT, NO_TOKEN, OPTIONS_WRONG_TYPE, PASSWORD_WRONG_TYPE } from "../../errors/Messages";
import type { IdResolvable } from "../../types/common";
import type { DocumentEditOptions, Document as ResponseDocument, DocumentCreateOptions } from "../../types/document";
import { CreateOptionsSchema, EditOptionsSchema } from "../../utils/schemas";
import { parseId } from "../../utils/parseId";
import { parsePassword } from "../../utils/parsePassword";
import { validateSchema } from "../../utils/schemaValidator";
import { Document } from "../../classes/Document";
import { stringify } from "../../utils/stringify";
import { WrongPassword, NotAllowed, DocumentNotFound, ImperialError } from "../../errors";
import { ErrorMessage } from "../errors/Messages";
import type { IdResolvable } from "../types/common";
import type { DocumentEditOptions, Document as ResponseDocument, DocumentCreateOptions } from "../types/document";
import { CreateOptionsSchema, EditOptionsSchema } from "../utils/schemas";
import { parseId } from "../utils/parseId";
import { parsePassword } from "../utils/parsePassword";
import { validateSchema } from "../utils/schemaValidator";
import { Document } from "../classes/Document";
import { stringify } from "../utils/stringify";

export class DocumentManager extends Base {
/**
Expand All @@ -34,9 +33,10 @@ export class DocumentManager extends Base {
*/
public async create(text: string, options: DocumentCreateOptions = {}): Promise<Document> {
// If no text or text is an emtpy string reutrn
if (!text) throw new Error(NO_TEXT);
if (!text) throw new Error(ErrorMessage("NO_TEXT"));

if (!options || typeof options !== "object" || Array.isArray(options)) throw new TypeError(OPTIONS_WRONG_TYPE);
if (!options || typeof options !== "object" || Array.isArray(options))
throw new TypeError(ErrorMessage("OPTIONS_WRONG_TYPE"));

const validateOptions = validateSchema(options as never, CreateOptionsSchema);

Expand Down Expand Up @@ -85,40 +85,22 @@ export class DocumentManager extends Base {
*/
public async get(id: IdResolvable, password?: string): Promise<Document> {
// Make the user inputed data encoded so it doesn't break stuff
const documentId = parseId(id, this.client.rest.hostnameCheckRegExp);

// If the id is emtpy return
if (!documentId) throw new Error(NO_ID);
const documentId = parseId(id, this.client.rest.hostnameRe);

// If no password was set try to extract it from the id
const documentPassword = password ?? parsePassword(id);

if (documentPassword && typeof documentPassword !== "string") throw new Error(PASSWORD_WRONG_TYPE);

try {
const data = await this.client.rest.request<ResponseDocument>(
"GET",
`/document/${encodeURIComponent(documentId)}${
documentPassword ? `?password=${encodeURIComponent(documentPassword)}` : ""
}`,
);

return new Document(this.client, data);
} catch (error) {
if (error instanceof ImperialError) {
switch (error.status) {
case 404:
throw new DocumentNotFound(error);
if (documentPassword && typeof documentPassword !== "string")
throw new TypeError(ErrorMessage("PASSWORD_WRONG_TYPE"));

case 401:
throw new WrongPassword(error);
const data = await this.client.rest.request<ResponseDocument>(
"GET",
`/document/${encodeURIComponent(documentId)}${
documentPassword ? `?password=${encodeURIComponent(documentPassword)}` : ""
}`,
);

default: // Empty because we throw bellow
}
}

throw error;
}
return new Document(this.client, data);
}

/**
Expand All @@ -142,18 +124,16 @@ export class DocumentManager extends Base {

public async edit(id: IdResolvable, text: string, options: DocumentEditOptions = {}): Promise<Document> {
// If no token return
if (!this.client.apiToken) throw new Error(NO_TOKEN);
if (!this.client.apiToken) throw new Error(ErrorMessage("NO_TOKEN"));

// Make the user inputed data encoded so it doesn't break stuff
const documentId = parseId(id, this.client.rest.hostnameCheckRegExp);

// If the id is emtpy return
if (!documentId) throw new Error(NO_ID);
const documentId = parseId(id, this.client.rest.hostnameRe);

// If no newText was provided reutrn
if (!text) throw new Error(NO_TEXT);
if (!text) throw new Error(ErrorMessage("NO_TEXT"));

if (!options || typeof options !== "object" || Array.isArray(options)) throw new TypeError(OPTIONS_WRONG_TYPE);
if (!options || typeof options !== "object" || Array.isArray(options))
throw new TypeError(ErrorMessage("OPTIONS_WRONG_TYPE"));

const validateOptions = validateSchema(options as never, EditOptionsSchema);

Expand All @@ -167,31 +147,15 @@ export class DocumentManager extends Base {

const content = stringify(text);

try {
const data = await this.client.rest.request<ResponseDocument>("PATCH", "/document", {
data: {
id: documentId,
content,
settings,
},
});

return new Document(this.client, data);
} catch (error) {
if (error instanceof ImperialError) {
switch (error.status) {
case 404:
throw new DocumentNotFound(error);

case 401:
throw new NotAllowed(error);

default: // Empty because we throw bellow
}
}

throw error;
}
const data = await this.client.rest.request<ResponseDocument>("PATCH", "/document", {
data: {
id: documentId,
content,
settings,
},
});

return new Document(this.client, data);
}

/**
Expand All @@ -202,30 +166,11 @@ export class DocumentManager extends Base {
*/
public async delete(id: IdResolvable): Promise<void> {
// If not token return
if (!this.client.apiToken) throw new Error(NO_TOKEN);
if (!this.client.apiToken) throw new Error(ErrorMessage("NO_TOKEN"));

// Make the user inputed data encoded so it doesn't break stuff
const documentId = parseId(id, this.client.rest.hostnameCheckRegExp);
const documentId = parseId(id, this.client.rest.hostnameRe);

// If the id is emtpy return
if (!documentId) throw new Error(NO_ID);

try {
await this.client.rest.request("DELETE", `/document/${encodeURIComponent(documentId)}`);
} catch (error) {
if (error instanceof ImperialError) {
switch (error.status) {
case 404:
throw new DocumentNotFound(error);

case 401:
throw new NotAllowed(error);

default: // Empty because we throw bellow
}
}

throw error;
}
await this.client.rest.request("DELETE", `/document/${encodeURIComponent(documentId)}`);
}
}
43 changes: 43 additions & 0 deletions src/lib/managers/Me.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type { Document as IDocument } from "../types/document";
import { Document } from "../classes/Document";
import { ErrorMessage } from "../errors/Messages";
import { Base } from "./Base";
import type { MeUser } from "../types/me";

export class MeManager extends Base {
/**
* Show current user
*/
public async get(): Promise<MeUser> {
if (!this.client.apiToken) throw new Error(ErrorMessage("NO_TOKEN"));

return this.client.rest.request<MeUser>("GET", "/user/@me");
}

/**
* Show recent documents for the current user
*/
public async recent(): Promise<Document[] | null> {
if (!this.client.apiToken) throw new Error(ErrorMessage("NO_TOKEN"));

const data = await this.client.rest.request<IDocument[]>("GET", "/user/@me/recentDocuments");

if (!data) return null;

return data.map((document) => new Document(this.client, document));
}

/**
* Change the icon of the current user
*/
public async setIcon(method: "github" | "gravatar", url: string): Promise<MeUser> {
if (!this.client.apiToken) throw new Error(ErrorMessage("NO_TOKEN"));

return this.client.rest.request<MeUser>("PATCH", "/user/@me/icon", {
data: {
method,
url,
},
});
}
}
21 changes: 21 additions & 0 deletions src/lib/managers/Users.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { User as IUser } from "../types/users";
import { User } from "../classes/User";
import { ErrorMessage } from "../errors/Messages";
import { Base } from "./Base";

export class UsersManager extends Base {
/**
* Get a user from Imperial.
* @param username - The username of the user to get.
* @example client.users.get("pxseu").then(console.log) // Logs the user to the console.
*/
public async get(username: string): Promise<User> {
if (!this.client.apiToken) throw new Error(ErrorMessage("NO_TOKEN"));
if (!username) throw new Error(ErrorMessage("NO_USERNAME"));
if (typeof username !== "string") throw new TypeError(ErrorMessage("USERNAME_WRONG_TYPE"));

const data = await this.client.rest.request<IUser>("GET", `/user/${encodeURIComponent(username)}`);

return new User(this.client, data);
}
}

0 comments on commit ffa4e2b

Please sign in to comment.