Skip to content

Commit

Permalink
V2.0.0 DEV 3 RELEASE
Browse files Browse the repository at this point in the history
  • Loading branch information
Abadima committed Aug 8, 2023
1 parent 2fadd59 commit eeaae43
Show file tree
Hide file tree
Showing 19 changed files with 220 additions and 140 deletions.
19 changes: 19 additions & 0 deletions Mini_Docs/functions/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

* [db](#db)
* [new db()](#new_db_new)
* [.getCollection(collection)](#db.getCollection) ⇒ <code>Collection</code>
* [.createOne(query)](#db.createOne) ⇒ <code>Promise.&lt;(UserResult\|LevelRoleResult)&gt;</code>
* [.deleteOne(query)](#db.deleteOne) ⇒ <code>Promise.&lt;boolean&gt;</code>
* [.findOne(query)](#db.findOne) ⇒ <code>Promise.&lt;(UserResult\|LevelRoleResult)&gt;</code>
Expand All @@ -19,6 +20,24 @@

Database class providing methods to interact with the database.

<a name="db.getCollection"></a>

### db.getCollection(collection) ⇒ <code>Collection</code>

Gets a collection from the database.

**Kind**: static method of [<code>db</code>](#db)
**Returns**: <code>Collection</code> - The collection.
**Throws**:

- <code>XpFatal</code> Throws an error if there is no database connection, or database type is invalid.

**Link**: https://simplyxp.js.org/docs/handlers/database#getCollection Documentation

| Param | Type | Description |
|------------|-------------------------|------------------------|
| collection | <code>collection</code> | The collection to get. |

<a name="db.createOne"></a>

### db.createOne(query) ⇒ <code>Promise.&lt;(UserResult\|LevelRoleResult)&gt;</code>
Expand Down
20 changes: 0 additions & 20 deletions Mini_Docs/functions/xplogs.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
## Classes

<dl>
<dt><a href="#XpFatal">XpFatal</a></dt>
<dd></dd>
<dt><a href="#XpLog">XpLog</a></dt>
<dd></dd>
</dl>

<a name="XpFatal"></a>

## XpFatal
Expand All @@ -33,14 +24,3 @@ Emits a simple error message
|---------|-------------------------|
| options | <code>errOptions</code> |

<a name="XpLog"></a>

## XpLog

**Kind**: global class
<a name="new_XpLog_new"></a>

### new XpLog()

Emits a log message

26 changes: 13 additions & 13 deletions Mini_Docs/migrate.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

* [migrate](#migrate)
* [new migrate()](#new_migrate_new)
* [.discord_xp(dbUrl, deleteOld)](#migrate.discord_xp) ⇒ <code>Promise.&lt;boolean&gt;</code>
* [.database(from)](#migrate.database) ⇒ <code>Promise.&lt;boolean&gt;</code>
* [.discord_xp(deleteOld)](#migrate.discord_xp) ⇒ <code>Promise.&lt;boolean&gt;</code>
* [.fromDB(dbType, connection)](#migrate.fromDB) ⇒ <code>Promise.&lt;boolean&gt;</code>

<a name="new_migrate_new"></a>

Expand All @@ -17,26 +17,25 @@ Migration functions

<a name="migrate.discord_xp"></a>

### migrate.discord\_xp(dbUrl, deleteOld) ⇒ <code>Promise.&lt;boolean&gt;</code>
### migrate.discord\_xp(deleteOld) ⇒ <code>Promise.&lt;boolean&gt;</code>

Effortlessly migrate from discord-xp to simply-xp.

**Kind**: static method of [<code>migrate</code>](#migrate)
**Returns**: <code>Promise.&lt;boolean&gt;</code> - - Returns true if migration is successful
**Throws**:

- <code>XpFatal</code> - If parameters are not provided correctly
- <code>XpLog.err</code> - If migration fails.

**Link**: `Documentation:` https://simplyxp.js.org/docs/migrate/discord_xp

| Param | Type | Description |
|-----------|----------------------|---------------------------------|
| dbUrl | <code>URL</code> | MongoDB URL |
| deleteOld | <code>boolean</code> | Delete old data after migration |
| Param | Type | Default | Description |
|-----------|----------------------|--------------------|---------------------------------|
| deleteOld | <code>boolean</code> | <code>false</code> | Delete old data after migration |

<a name="migrate.database"></a>
<a name="migrate.fromDB"></a>

### migrate.database(from) ⇒ <code>Promise.&lt;boolean&gt;</code>
### migrate.fromDB(dbType, connection) ⇒ <code>Promise.&lt;boolean&gt;</code>

Effortlessly migrate from MongoDB to SQLite. (or vice versa)

Expand All @@ -48,7 +47,8 @@ Effortlessly migrate from MongoDB to SQLite. (or vice versa)

**Link**: `Documentation:` https://simplyxp.js.org/docs/migrate/database

| Param | Type |
|-------|---------------------------------------------------------------------|
| from | <code>&quot;mongodb&quot;</code> \| <code>&quot;sqlite&quot;</code> |
| Param | Type |
|------------|---------------------------------------------------------------------|
| dbType | <code>&quot;mongodb&quot;</code> \| <code>&quot;sqlite&quot;</code> |
| connection | <code>Database</code> \| <code>MongoClient</code> |

2 changes: 1 addition & 1 deletion Mini_Docs/reset.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ Reset user levels to 0 in a guild
|----------|----------------------|--------------------|--------------------------------|
| userId | <code>string</code> | | |
| guildId | <code>string</code> | | |
| username | <code>string</code> | | |
| erase | <code>boolean</code> | <code>false</code> | Erase user entry from database |
| username | <code>string</code> | | |

Binary file modified Tests/leaderboard.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
13 changes: 9 additions & 4 deletions Tests/test.cjs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
const xp = require("../lib/xp.js");

const MongoURL = "mongodb+srv://test-bot:[email protected]/?retryWrites=true&w=majority";

async function test(dbType) {

switch (dbType) {
case "mongodb":
await xp.connect("mongodb+srv://test-bot:[email protected]/?retryWrites=true&w=majority", {
await xp.connect(MongoURL, {
type: "mongodb",
debug: true
});
Expand All @@ -27,16 +29,19 @@ async function test(dbType) {

await xp.create("1234567894", "0987654321", "Snowball");


await xp.setLevel("1234567890", "0987654321", Infinity);

await xp.setLevel("1234567891", "0987654321", 50);

await xp.setLevel("1234567893", "0987654321", 420690000);

await xp.setLevel("1234567892", "0987654321", 100).then(console.log)
await xp.setLevel("1234567892", "0987654321", 0);

await xp.addXP("1234567892", "0987654321", 650);

await xp.reset("1234567892", "0987654321").then(console.log);

await xp.addXP("1234567892", "0987654321", 650).then(console.log)
await xp.fetch("1234567892", "0987654321").then(console.log);

await xp.rankCard(
{id: "0987654321", name: "SimplyTests"},
Expand Down
Binary file modified Tests/test.db
Binary file not shown.
31 changes: 30 additions & 1 deletion [email protected]
Original file line number Diff line number Diff line change
@@ -1,5 +1,33 @@
# VERSION 2@DEV CHANGELOGS

## [DEV 3](https://github.com/Abadima/simply-xp/releases/tag/v2.0.0-dev.2)

### Additions
- Added `db.getCollection()` feature, useful for custom database implementations.
- Implemented `migrate.fromDB()`, from MongoDB to SQLite. (Support for SQLite to MongoDB coming soon)

### ⚠️ Breaking Changes

- `migrate.discord_xp()` removes `dbUrl` parameter.
- `migrate.database()` => `migrate.fromDB()`
- `reset()` switches `username` and `erase` parameters around.

### Changes

- Overhauled `migrate.discord_xp()` function, should fix issues and remove unnecessary requirements.

### Bug Fixes

- Fix `reset()` not properly resetting users.

## [DEV 2 FIX 0](https://github.com/Abadima/simply-xp/releases/tag/v2.0.0-dev.2)

### Bug Fixes

- Fix SQLite Issues (`updateOne()`, `createOne()`), "Collection Mismatch" error, and `name` not being added on
create/update.
- Fix `convertFrom()`, `setLevel()`, `setXP()`, `addLevel()`, `addXP()` throwing error when "0" is passed as value

## [DEV 2](https://github.com/Abadima/simply-xp/releases/tag/v2.0.0-dev.2)

### Additions
Expand Down Expand Up @@ -34,7 +62,8 @@
- `fetch()` has a new `username` parameter, to automatically create the user if it doesn't exist.
- `connect()` now accepts `auto_create`, All functions can create the user if it doesn't exist, avoiding errors.
- Updated JSDocs, changed some types to interfaces.
- `addLevel(), addXP(), setLevel(), setXP()` now has a `username` parameter, to automatically create the user if it doesn't exist.
- `addLevel(), addXP(), setLevel(), setXP()` now has a `username` parameter, to automatically create the user if it
doesn't exist.
- `rank()` will now auto create the user if it doesn't exist if `auto_create` is set to `true`.

## [DEV 0 FIX 2](https://github.com/Abadima/simply-xp/releases/tag/v2.0.0-dev.0)
Expand Down
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "simply-xp",
"version": "2.0.0-dev.2",
"version": "2.0.0-dev.3",
"description": "The easiest way to implement xp system",
"main": "lib/xp.js",
"scripts": {
Expand Down Expand Up @@ -45,14 +45,14 @@
"devDependencies": {
"@types/better-sqlite3": "^7.6.4",
"@types/node": "^20.4.8",
"@typescript-eslint/eslint-plugin": "^6.2.1",
"@typescript-eslint/parser": "^6.2.1",
"@typescript-eslint/eslint-plugin": "^6.3.0",
"@typescript-eslint/parser": "^6.3.0",
"better-sqlite3": "8.5.0",
"discord.js": "^14.12.1",
"eslint": "^8.46.0",
"guilded.ts": "^0.20.2",
"jsdoc-to-markdown": "^8.0.0",
"mongodb": "5.7.0",
"mongodb": "^5.7.0",
"typescript": "^5.1.6",
"uglify-js": "^3.17.4"
},
Expand Down
2 changes: 1 addition & 1 deletion src/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export async function addLevel(userId: string, guildId: string, level: number, u

if (!guildId) throw new XpFatal({function: "addLevel()", message: "Guild ID was not provided"});

if (!level) throw new XpFatal({function: "addLevel()", message: "Level was not provided"});
if (isNaN(level)) throw new XpFatal({function: "addLevel()", message: "Level was not provided"});

const user = await db.findOne({
collection: "simply-xps", data: {user: userId, guild: guildId}
Expand Down
28 changes: 7 additions & 21 deletions src/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,30 +59,17 @@ export async function connect(uri: string, options: ConnectionOptions = {type: u

xp.database.exec(`CREATE TABLE IF NOT EXISTS "simply-xps"
(
user
TEXT
UNIQUE,
guild
TEXT,
xp
INTEGER
DEFAULT
0,
level
INTEGER
DEFAULT
0
user TEXT NOT NULL,
guild TEXT NOT NULL,
name TEXT DEFAULT "Unknown",
level INTEGER DEFAULT 0,
xp INTEGER DEFAULT 0
)`
);
xp.database.exec(`CREATE TABLE IF NOT EXISTS "simply-xp-levelroles"
(
gid
TEXT
UNIQUE,
lvlrole
TEXT
NOT
NULL
gid TEXT UNIQUE,
lvlrole TEXT NOT NULL
)`
);
} catch (error: unknown) {
Expand Down Expand Up @@ -140,7 +127,6 @@ export async function checkPackageVersion(type: "mongodb" | "sqlite"): Promise<b
try {
const mongoPackage = await import("mongodb/package.json");
return parseInt(mongoPackage.version.substring(0, 1)) >= 4;

} catch (_) {
XpLog.info("checkPackageVersion()", "Installing MongoDB [5.x] | Please wait...");
execSync(`${await getPackageManager()} add [email protected]`);
Expand Down
8 changes: 2 additions & 6 deletions src/create.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {XpFatal, XpLog} from "./functions/xplogs";
import {XpFatal} from "./functions/xplogs";
import {UserResult} from "./functions/database";

/**
Expand All @@ -16,15 +16,11 @@ export async function create(userId: string, guildId: string, username: string):
if (!guildId) throw new XpFatal({function: "create()", message: "Guild ID was not provided"});
if (!username) throw new XpFatal({function: "create()", message: "Username was not provided"});

// TODO: Remove this warning in the next DEV release
XpLog.warn("create()", "We just swapped userId with guildId again, this warning will be removed in the next DEV release.");

const {db} = await import("./functions/database"),
user = await db.findOne({collection: "simply-xps", data: {user: userId, guild: guildId}}) as UserResult;

if (user) return user;
return await db.createOne({
collection: "simply-xps", data: {name: username, user: userId, guild: guildId, level: 0, xp: 0}
}) as UserResult;
}

}
26 changes: 21 additions & 5 deletions src/functions/database.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {Document, MongoClient} from "mongodb";
import {Collection, Document, MongoClient} from "mongodb";
import {Database} from "better-sqlite3";
import {XpFatal} from "./xplogs";
import {xp} from "../../xp";
Expand Down Expand Up @@ -74,6 +74,20 @@ export type LevelRoleResult = {
* @class db
*/
export class db {

/**
* Gets a collection from the database.
* @param {collection} collection - The collection to get.
* @link https://simplyxp.js.org/docs/handlers/database#getCollection Documentation
* @returns {Collection} The collection.
* @throws {XpFatal} Throws an error if there is no database connection, or database type is invalid.
*/
static getCollection(collection: string): Collection {
if (!xp.database) throw new XpFatal({function: "getCollection()", message: "No database connection"});
if (xp.dbType !== "mongodb") throw new XpFatal({function: "getCollection()", message: "MongoDB has to be your database type to use this function."});
return (xp.database as MongoClient).db().collection(collection);
}

/**
* Creates one document in the database.
*
Expand All @@ -93,7 +107,7 @@ export class db {
break;

case "sqlite":
if (query.collection === "simply-xps") result = (xp.database as Database).prepare("INSERT INTO \"simply-xps\" (user, guild, xp, level) VALUES (?, ?, ?, ?)").run(query.data.user, query.data.guild, query.data.xp, query.data.level);
if (query.collection === "simply-xps") result = (xp.database as Database).prepare("INSERT INTO \"simply-xps\" (user, guild, name, xp, level) VALUES (?, ?, ?, ?, ?)").run(query.data.user, query.data.guild, query.data?.name, query.data.xp, query.data.level);
else result = (xp.database as Database).prepare("INSERT INTO \"simply-xp-levelroles\" (guild, level, role) VALUES (?, ?, ?)").run(query.data.guild, query.data.level, query.data.roles);
break;
}
Expand Down Expand Up @@ -196,9 +210,11 @@ export class db {
break;

case "sqlite":
if (filter.collection === "simply-xps" && update.collection === "simply-xps") (xp.database as Database).prepare("UPDATE \"simply-xps\" SET xp = ?, level = ? WHERE guild = ? AND user = ?").run(update.data.xp, update.data.level, filter.data.guild, filter.data.user);
if (filter.collection === "simply-xps" && update.collection === "simply-xp-levelroles") (xp.database as Database).prepare("UPDATE \"simply-xp-levelroles\" SET role = ? WHERE guild = ? AND level = ?").run(update.data.roles, filter.data.guild, filter.data.level);
else throw new XpFatal({function: "updateOne()", message: "Collection mismatch, expected same collection on both filter and update."});
if (filter.collection === "simply-xps" && update.collection === "simply-xps") (xp.database as Database).prepare("UPDATE \"simply-xps\" SET name = ?, xp = ?, level = ? WHERE guild = ? AND user = ?").run(update.data?.name, update.data.xp, update.data.level, filter.data.guild, filter.data.user);
else if (filter.collection === "simply-xp-levelroles" && update.collection === "simply-xp-levelroles") (xp.database as Database).prepare("UPDATE \"simply-xp-levelroles\" SET role = ? WHERE guild = ? AND level = ?").run(update.data.roles, filter.data.guild, filter.data.level);
else throw new XpFatal({
function: "updateOne()", message: "Collection mismatch, expected same collection on both filter and update."
});
}
return db.findOne(update);
}
Expand Down
3 changes: 2 additions & 1 deletion src/functions/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ interface NewClientOptions {
* @throws {XpFatal} If an invalid type is provided or if the value is not provided.
*/
export function convertFrom(value: number, type: "xp" | "level" = "level"): number {
if (!value) throw new XpFatal({function: "convertFrom()", message: "Value was not provided"});
if (isNaN(value)) throw new XpFatal({function: "convertFrom()", message: "Value was not provided"});
if (type !== "xp" && type !== "level") throw new XpFatal({
function: "convert()", message: "Invalid type provided"
});
Expand All @@ -53,6 +53,7 @@ export function convertFrom(value: number, type: "xp" | "level" = "level"): numb
*/
export function updateOptions(clientOptions: NewClientOptions): void {
if (!clientOptions) throw new XpFatal({function: "updateOptions()", message: "Options were not provided"});

if (typeof clientOptions !== "object") throw new XpFatal({
function: "updateOptions()", message: "Options must be an object"
});
Expand Down
Loading

0 comments on commit eeaae43

Please sign in to comment.