Skip to content

Commit

Permalink
Merge pull request #7 from Con-JS-Development/development
Browse files Browse the repository at this point in the history
New Dynamic Properties Database
  • Loading branch information
conmaster2112 authored Dec 13, 2023
2 parents ef6d801 + 61d0b82 commit 51262d2
Show file tree
Hide file tree
Showing 6 changed files with 382 additions and 878 deletions.
98 changes: 54 additions & 44 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Con-Databases
This package contains three types of databases, JsonDatabase, NBTDatabase, CustomDatabase.
Each of these database types supports all possible [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) class operations from ECMAScript, which means.
New version of JsonDatabase is based on dynamic properties.
This database supports all possible [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) class operations from ECMAScript.
- [Starting Using Con-Databases](./docs/HOW_TO_SETUP.md)
- [Using CustomDatabase](./docs/CUSTOM_DATABASE.md) *(Soon)*
- [Basic API documentation](./docs/API-Documentation.md)

### Inherited from Map
- size: number of properties
Expand All @@ -16,58 +16,68 @@ Each of these database types supports all possible [Map](https://developer.mozil
- has(key: string): returns true when database has a value for that key
- keys(): returns iterbale of keys
- values(): returns iterable of values
### Additional Methods
- load(): will load database from provided scoreboard
- loadAsync(): will load database asynchonously from provided scoreboard
- rebuild(): when database is deleted by user in the world you can call rebuild to save loaded data without lost
- rebuildAsync(): same as rebuild() but asyncronouse
### Additional Properties
- objective: returns scoreboard objective what is database binded to
- id: returns id of the objective
- loaded: returns boolean, true when database is loaded
- maxLength: max size of key and value after parsed via parse
- savingMode: mode when your database is saving your data after change
- OneTimeSave: Saving after value was changed
- EndTickSave: Saving at the end of the tick, ater any changes occurs
- IntervalTick: Saving Every interval if changes occurs

### Database Types
- JsonDatabase, is saving data in JSON form. (SuperFast/EasyToRead)
- NBTDatabase, is saving data in NBT form. (Fast/HardToRead)
- Custom, is saving data in format of provided parser (undefined/undefined)
### Additional Methods & Properties
- dispose(): dispose the current instance of database anc clears it chache, saved data are not lost!
- isValid(): returns true when source is valid and database is not disposed
- isDisposed: property returns if database is disposed
# Other examples

### Dual instance security!
```js
const myDB1 = new JsonDatabase("sameId");
const myDB2 = new NBTDatabase("sameId"); //returns JsonDatabase because database with same id "sameId" was already created.
const myDB1 = new JsonDatabase(world,"sameId");
const myDB2 = new WorldDatabase("sameId"); //returns JsonDatabase because database with same id "sameId" and same source was already created.

console.log(myDB1 === myDB2); //true the very same instance!
```

### Example
```js
// INITIALIZATION OF DATABASE
const myDB = new JsonDatabase("MyIdentifier").load();
const myDB = new NBTDatabase("MyIdentifier2").load();
const myDB = new CustomDatabase(JSON /* JSON is parser */,"MyIdentifier3").load();

//using (get/set) to (read/write) data (from/to) database
const worldOpenedCount = myDB.get("openCount")??0;
myDB.set("openCount", ++worldOpenedCount);

//getting all data saved in database
for(const [key, value] of myDB.entries()){
console.warn(key, value);
import {world} from "@minecraft/server";
import {JsonDatabase} from "./con-database.js";

const db = new WorldDatabase("my id");

db.set("key1", "value1");
db.set("key2", {isComplexObject: true});

console.warn(db.get("key1")); // "value1"

db.delete("key1");

console.warn(db.get("key1")); // undefined

// Iterating over the map using for loop
for (const [key, value] of db) {
console.warn(`${key} = ${value}`);
}

//clearing database
myDB.clear();
db.clear();

// Getting the size of the map
console.warn(db.size); // 0
```
## Example saving deaths for each player
Each key is unique to its player because key include players id, so database keys looks like
```
5648463deaths
6843684deaths
6545463deaths
```
Code
```js
import {world} from "@minecraft/server";
import {WorldDatabase} from "databases.js";

const stats = new WorldDatabase("playerStats");

world.afterEvents.entityDie.subscribe(({deadEntity})=>
setDeaths(deadEntity,getDeaths(deadEntity) + 1);
,{entityTypes:["mineraft:player"]});


//removing specific value
myDB.delete("Josh");
function getDeaths(player){
return stats.get(player.id + "deaths")??0;}

//forEaching every element in scoreboard
myDB.forEach((value,key)=>{
console.warn(key, value);
});
function setDeaths(player,deaths){
stats.set(player.id + "deaths",deaths);}
```
192 changes: 12 additions & 180 deletions database.d.ts
Original file line number Diff line number Diff line change
@@ -1,182 +1,14 @@
import {ScoreboardObjective, ScoreboardIdentity, Entity} from "@minecraft/server";
//////////////////////////////////////
// NBT-SERIALIZER.D.TS
//////////////////////////////////////

type StringBase = 16|8|32;
type IStreamType = number | number | {buffer: ArrayBuffer};
declare class Stream extends DataView{
constructor(buffer: ArrayBuffer | number, offset?: number)
protected __offset__: number
readonly offset: number
readonly size: number
readonly EndOfStream: boolean
setOffset(num: number): void
static fromString(text: string, options?: {bufferLength?: number, base?:StringBase},...params: any): Stream
/**@param {Stream} stream @param {8|16|32} base*/
static toString(stream: Stream, base?: StringBase): string
toString(base?: StringBase): string
}
declare class BinaryStreamWriter extends Stream{
constructor(stream: IStreamType)
writeBytes(buffer: ArrayBuffer,length?:number ): number
writeString(text: string, base?: StringBase): number
writeByte(num: number): number
writeUint8(num: number): number
writeInt8(num: number): number
writeInt16(num: number): number
writeUint16(num: number): number
writeInt32(num: number): number
writeUint32(num: number): number
writeFloat32(num: number): number
writeFloat64(num: number): number
static fromString(text: string, options?: {bufferLength?: number, base?:StringBase},...params: any): BinaryStreamWriter
}
declare class BinaryStreamReader extends Stream{
constructor(stream: IStreamType)
readBytes(length?: number): Uint8Array
readString(length: number, base?: StringBase):string
readByte():number
readUint8():number
readInt8():number
readInt16():number
readUint16():number
readInt32():number
readUint32():number
readFloat32():number
readFloat64():number
static fromString(text: string, options?: {bufferLength?: number, base?:StringBase},...params: any): BinaryStreamReader
}
declare class EndOfStreamError extends Error{}
declare enum NBTTypes {
"EndOfCompoud"=0,
"Compoud"=1,
"Array"=2,
"TypedArray"=3,
"Uint8"=4,
"Uint16"=5,
"Int32"=6,
"Double"=7,
"String"=8,
"Empty"=9,
"Boolean"=10
}
declare class NBTStreamWriter extends BinaryStreamWriter{
constructor(stream: IStreamType, options?: object | NBTStreamWriter)
protected __options__: NBTWriterOptions;
writeTypedArray<t>(array: Array<t>): number
writeBoolean(bool: boolean):number
writeString(text: string): number
writeArray(array: any[]): number
writeCompoud(object: object): number
writeEmpty(): number
writeType(type: NBTTypes): number
static fromString(text: string, options?: {bufferLength?: number, base?:StringBase},...params: any): NBTStreamWriter
}
declare class NBTStreamReader extends BinaryStreamReader{
constructor(stream: IStreamType, options?: object | NBTReaderOptions)
protected __options__: NBTReaderOptions;
readTypedArray(): Array<any>
readBoolean(): boolean
readString(): string
readArray(): any[]
readCompoud(): object
readEmpty(): undefined
readType(): NBTTypes
static fromString(text: string, options?: {bufferLength?: number, base?:StringBase},...params: any): NBTStreamReader
}
declare const NBT: {
ReadNBT(stream: NBTStreamReader): any
WriteNBT(data: any, stream: NBTStreamWriter, type?: NBTTypes): number
getType(data: any): NBTTypes
stringify(object:any, options?: NBTWriterOptions): string
parse(string: string, options?: NBTReaderOptions): any
createNewWriters<t extends Partial<typeof defaultWriters>>(object?: t): t & typeof defaultWriters
createNewReaders<t extends Partial<typeof defualtReaders>>(object?: t): t & typeof defualtReaders
}
type WriterCall = (stream: NBTStreamWriter, data: any)=>number
type ReaderCall = (stream: NBTStreamReader)=>any
declare const defaultWriters: {
[NBTTypes.Compoud]:WriterCall,
[NBTTypes.Empty]:WriterCall,
[NBTTypes.Array]:WriterCall,
[NBTTypes.String]:WriterCall,
[NBTTypes.Boolean]:WriterCall,
[NBTTypes.Uint8]:WriterCall,
[NBTTypes.Uint16]:WriterCall,
[NBTTypes.Int32]:WriterCall,
[NBTTypes.Double]:WriterCall,
[NBTTypes.TypedArray]:WriterCall
}
declare const defualtReaders: {
[NBTTypes.Compoud]:ReaderCall,
[NBTTypes.Empty]:ReaderCall,
[NBTTypes.Array]:ReaderCall,
[NBTTypes.String]:ReaderCall,
[NBTTypes.Boolean]:ReaderCall,
[NBTTypes.Uint8]:ReaderCall,
[NBTTypes.Uint16]:ReaderCall,
[NBTTypes.Int32]:ReaderCall,
[NBTTypes.Double]:ReaderCall,
[NBTTypes.TypedArray]:ReaderCall
}
declare class NBTStreamOptions{
nbtTypes: object & NBTTypes
getType:(data: any)=>NBTStreamOptions["nbtTypes"][keyof NBTStreamOptions["nbtTypes"]]
}
declare class NBTWriterOptions extends NBTStreamOptions{
writers: ReturnType<typeof NBT["createNewWriters"]>;
}
declare class NBTReaderOptions extends NBTStreamOptions{
readers: ReturnType<typeof NBT["createNewReaders"]>;
}




//////////////////////////////////////
// DATABASE.JS
//////////////////////////////////////
export enum DatabaseSavingModes {
OneTimeSave="OneTimeSave",
EndTickSave="EndTickSave",
TickInterval="TickInterval"
}
export enum ChangeAction {
Change=0,
Remove=1
}
/**@extends {Map<string,any>}*/
declare class ScoreboardDatabaseManager extends Map<string,any>{
private _saveMode_: DatabaseSavingModes;
private _loadingPromise_?: Promise<this>;
private hasChanges: boolean;
private readonly _scoreboard_: ScoreboardObjective;
protected readonly _source_: Map<string,string|ScoreboardIdentity|Entity>;
protected readonly _parser_: {stringify:(data: any)=>string,parse:(data: string)=>any};
constructor(objective: string | ScoreboardObjective, saveMode?: DatabaseSavingModes);
constructor(objective: string | ScoreboardObjective, saveMode: DatabaseSavingModes.EndTickSave, interval?: number);
/**@inheritdoc */
set(key: string, value: any): this
/**@inheritdoc */
import {World, Entity} from "@minecraft/server";
declare class DynamicDatabase extends Map{
protected constructor();
set(key: string, value: any)
delete(key: string): boolean
/**@inheritdoc */
clear(): void
load(): this
loadAsync(): Promise<this>
rebuild(): this;
rebuildAsync(): Promise<this>;
readonly objective: ScoreboardObjective
readonly id: string;
readonly loaded: boolean;
readonly maxLength: number;
readonly savingMode: DatabaseSavingModes;
readonly type: "DefualtJsonType"| "JsonType"| "NBTType" | "CustomType";
readonly loadingAwaiter: Promise<this>;
}
export class JsonDatabase extends ScoreboardDatabaseManager{}
export class NBTDatabase extends ScoreboardDatabaseManager{}
export class CustomDatabase extends ScoreboardDatabaseManager{
constructor(parser: {parse:(data:string)=>any,stringify:(data: any)=>string}, objective: string | ScoreboardObjective, saveMode?: DatabaseSavingModes);
constructor(parser: {parse:(data:string)=>any,stringify:(data: any)=>string}, objective: string | ScoreboardObjective, saveMode: DatabaseSavingModes.EndTickSave, interval?: number);
}
isValid(): boolean
dispose(): void
readonly isDisposed: boolean
}
//@ts-ignore
export class JsonDatabase extends DynamicDatabase{ constructor(source: World | Entity, id: string); }
//@ts-ignore
export class WorldDatabase extends JsonDatabase { constructor(id: string) }
Loading

0 comments on commit 51262d2

Please sign in to comment.