Skip to content

Commit 2f5d7a0

Browse files
Merge pull request #4 from Con-JS-Development/development
Dual instance security!
2 parents a27050e + b5b2ee5 commit 2f5d7a0

5 files changed

Lines changed: 57 additions & 24 deletions

File tree

README.md

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,13 @@ Each of these database types supports all possible [Map](https://developer.mozil
99
- entries(): generator of all values [key, value]
1010
- forEach(callBack: (value, key, this)=>void): for each all elements and call provided function for that
1111
- get(key: string): returns value for specific key
12-
- set(key: string, value: any): sets new value for provided key
12+
- set(key: string: value: any): sets new value for provided key
13+
- has(key: string): returns true when database has a value for that key
1314
- keys(): returns iterbale of keys
1415
- values(): returns iterable of values
1516
### Additional Methods
1617
- load(): will load database from provided scoreboard
17-
- loadAsync(): will load database asynchonously from profived scoreboard
18+
- loadAsync(): will load database asynchonously from provided scoreboard
1819
- rebuild(): when database is deleted by user in the world you can call rebuild to save loaded data without lost
1920
- rebuildAsync(): same as rebuild() but asyncronouse
2021
### Additional Properties
@@ -32,12 +33,20 @@ Each of these database types supports all possible [Map](https://developer.mozil
3233
- NBTDatabase, is saving data in NBT form. (Fast/HardToRead)
3334
- Custom, is saving data in format of provided parser (undefined/undefined)
3435

36+
### Dual instance security!
37+
```js
38+
const myDB1 = new JsonDatabase("sameId");
39+
const myDB2 = new NBTDatabase("sameId"); //returns JsonDatabase because database with same id "sameId" was already created.
40+
41+
console.log(myDB1 === myDB2); //true the very same instance!
42+
```
43+
3544
### Example
3645
```js
3746
// INITIALIZATION OF DATABASE
3847
const myDB = new JsonDatabase("MyIdentifier").load();
39-
const myDB = new NBTDatabase("MyIdentifier").load();
40-
const myDB = new CustomDatabase(JSON /* JSON is parser */,"MyIdentifier").load();
48+
const myDB = new NBTDatabase("MyIdentifier2").load();
49+
const myDB = new CustomDatabase(JSON /* JSON is parser */,"MyIdentifier3").load();
4150

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

database.d.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -149,18 +149,18 @@ export enum ChangeAction {
149149
/**@extends {Map<string,any>}*/
150150
declare class ScoreboardDatabaseManager extends Map<string,any>{
151151
private _saveMode_: DatabaseSavingModes;
152+
private _loadingPromise_?: Promise<this>;
152153
private hasChanges: boolean;
153-
readonly maxLength: number;
154154
private readonly _scoreboard_: ScoreboardObjective;
155155
protected readonly _source_: Map<string,string|ScoreboardIdentity|Entity>;
156156
protected readonly _parser_: {stringify:(data: any)=>string,parse:(data: string)=>any};
157-
readonly savingMode: DatabaseSavingModes;
158-
constructor(objective, saveMode: DatabaseSavingModes);
159-
constructor(objective, saveMode: DatabaseSavingModes.EndTickSave, interval?: number);
157+
constructor(objective: string | ScoreboardObjective, saveMode?: DatabaseSavingModes);
158+
constructor(objective: string | ScoreboardObjective, saveMode: DatabaseSavingModes.EndTickSave, interval?: number);
160159
/**@inheritdoc */
161160
set(key: string, value: any): this
162161
/**@inheritdoc */
163162
delete(key: string): boolean
163+
/**@inheritdoc */
164164
clear(): void
165165
load(): this
166166
loadAsync(): Promise<this>
@@ -169,10 +169,14 @@ declare class ScoreboardDatabaseManager extends Map<string,any>{
169169
readonly objective: ScoreboardObjective
170170
readonly id: string;
171171
readonly loaded: boolean;
172+
readonly maxLength: number;
173+
readonly savingMode: DatabaseSavingModes;
174+
readonly type: "DefualtJsonType"| "JsonType"| "NBTType" | "CustomType";
175+
readonly loadingAwaiter: Promise<this>;
172176
}
173177
export class JsonDatabase extends ScoreboardDatabaseManager{}
174178
export class NBTDatabase extends ScoreboardDatabaseManager{}
175179
export class CustomDatabase extends ScoreboardDatabaseManager{
176-
constructor(parser: {parse:(data:string)=>any,stringify:(data: any)=>string}, objective: string | ScoreboardObjective, saveMode: DatabaseSavingModes);
180+
constructor(parser: {parse:(data:string)=>any,stringify:(data: any)=>string}, objective: string | ScoreboardObjective, saveMode?: DatabaseSavingModes);
177181
constructor(parser: {parse:(data:string)=>any,stringify:(data: any)=>string}, objective: string | ScoreboardObjective, saveMode: DatabaseSavingModes.EndTickSave, interval?: number);
178182
}

database.js

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,9 @@ NBTReaderOptions.prototype.readers = defualtReaders;
428428
// DATABASE.JS
429429
///////////////////////////////////////////////////
430430
const {scoreboard} = world, {FakePlayer} = ScoreboardIdentityType;
431+
432+
const databases = new Map();
433+
431434
const split = "\n_`Split`_\n";
432435
function endTickCall(callback){
433436
system.run(()=>system.run(()=>system.run(callback)));
@@ -481,13 +484,14 @@ class ScoreboardDatabaseManager extends Map{
481484
_saveMode_;
482485
/**@private */
483486
hasChanges = false;
487+
/**@private */
488+
_loadingPromise_;
484489
/**@readonly */
485490
get maxLength(){return 30e3;}
486491
/**@private @type {ScoreboardObjective}*/
487492
_scoreboard_;
488493
/**@protected @type {Map<string,string|ScoreboardIdentity|Entity>} */
489494
_source_;
490-
_onHandleLost_;
491495
/**@protected @readonly @type {{stringify:(data: any)=>string,parse:(data: string): any}} */
492496
get _parser_(){return JSON;}
493497
get savingMode(){return this._saveMode_;}
@@ -500,6 +504,7 @@ class ScoreboardDatabaseManager extends Map{
500504
if(!objective) throw new RangeError("Firt parameter si not valid: " + objective);
501505
if(typeof objective !== "string" && !objective instanceof ScoreboardObjective) throw new RangeError("Firt parameter si not valid: " + objective);
502506
this._scoreboard_ = typeof objective === "string"?(scoreboard.getObjective(objective)??scoreboard.addObjective(objective,objective)):objective;
507+
if(databases.has(this.id)) return databases.get(this.id);
503508
this._nameId_ = this.id;
504509
this._source_ = new Map();
505510
this._changes_ = new Map();
@@ -514,6 +519,7 @@ class ScoreboardDatabaseManager extends Map{
514519
}
515520
},this.interval);
516521
}
522+
databases.set(this.id,this);
517523
}
518524
load(){
519525
if(this._loaded_) return this;
@@ -527,17 +533,21 @@ class ScoreboardDatabaseManager extends Map{
527533
this._loaded_=true;
528534
return this;
529535
}
530-
async loadAsync(){
531-
if(this._loaded_) return this;
532-
for (const participant of this._scoreboard_.getParticipants()) {
533-
const {displayName,type} = participant;
534-
if(type !== FakePlayer) continue;
535-
const [name,data] = displayName.split(split);
536-
this._source_.set(name,participant);
537-
super.set(name,this._parser_.parse(data));
538-
}
539-
this._loaded_=true;
540-
return this;
536+
loadAsync(){
537+
if(this._loaded_) return this._loadingPromise_??Promise.resolve(this);
538+
const promise = (async ()=>{
539+
for (const participant of this._scoreboard_.getParticipants()) {
540+
const {displayName,type} = participant;
541+
if(type !== FakePlayer) continue;
542+
const [name,data] = displayName.split(split);
543+
this._source_.set(name,participant);
544+
super.set(name,this._parser_.parse(data));
545+
}
546+
this._loaded_=true;
547+
return this;
548+
})();
549+
this._loadingPromise_ = promise;
550+
return promise;
541551
}
542552
/**@inheritdoc */
543553
set(key, value){
@@ -554,6 +564,7 @@ class ScoreboardDatabaseManager extends Map{
554564
this._onChange_(key,null,ChangeAction.Remove);
555565
return super.delete(key);
556566
}
567+
/**@inheritdoc */
557568
clear(){
558569
if(!this._loaded_) throw new ReferenceError("Database is not loaded");
559570
for (const [key,value] of this.entries()) this.delete(key,value);
@@ -569,6 +580,9 @@ class ScoreboardDatabaseManager extends Map{
569580
get id(){return this._scoreboard_.id;}
570581
/**@readonly @returns {boolean} */
571582
get loaded(){return this._loaded_;}
583+
/**@readonly @returns {DefualtJsonType} */
584+
get type(){return "DefualtJsonType";}
585+
get loadingAwaiter(){return this._loadingPromise_??this.loadAsync();}
572586
rebuild(){
573587
if(this.objective?.isValid()) return;
574588
const newScores = scoreboard.addObjective(this._nameId_,this._nameId_);
@@ -595,15 +609,19 @@ class ScoreboardDatabaseManager extends Map{
595609
return this;
596610
}
597611
}
598-
export class JsonDatabase extends ScoreboardDatabaseManager{}
612+
export class JsonDatabase extends ScoreboardDatabaseManager{
613+
get type(){return "JsonType";}
614+
}
599615
export class NBTDatabase extends ScoreboardDatabaseManager{
600616
get _parser_() {return NBT;};
617+
get type(){return "NBTType";}
601618
}
602619
export class CustomDatabase extends ScoreboardDatabaseManager{
603620
constructor(parser,...params){
604621
super(params);
605622
this._parser_ = parser;
606623
}
624+
get type(){return "CustomType";}
607625
}
608626
function generateRandomString(length) {
609627
let result = '';

packs/BP/manifest.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
}
1717
],
1818
"dependencies": [
19-
{"module_name": "@minecraft/server","version": "1.5.0-beta"},
19+
{"module_name": "@minecraft/server","version": "1.6.0-beta"},
2020
{"module_name": "@minecraft/server-ui","version": "1.2.0-beta"}
2121
],
2222
"capabilities": ["script_eval"]

packs/BP/scripts/index.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1-
import { DatabaseSavingModes, NBTDatabase } from "db";
1+
import { DatabaseSavingModes, NBTDatabase, JsonDatabase } from "database";
22

33

44
const a = new NBTDatabase("sus2",DatabaseSavingModes.OneTimeSave,50).load();
5+
const b = new JsonDatabase("sus2");
6+
console.warn(a === b);
57
a.set("sussy",{jerremy:(a.get("sussy")?.jerremy??0) + 1});
68

79
console.warn("Current sussy count is " + a.get("sussy").jerremy);

0 commit comments

Comments
 (0)