Skip to content

Commit

Permalink
style: apply automatic eslint fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
hasezoey committed Aug 6, 2021
1 parent d1e8891 commit ab98557
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 39 deletions.
51 changes: 32 additions & 19 deletions src/autoIncrement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export function AutoIncrementSimple(
// check if all fields are valid
for (const field of fields) {
const schemaField = schema.path(field.field);

// check if the field is even existing
if (isNullOrUndefined(schemaField)) {
throw new Error(`Field "${field.field}" does not exists on the Schema!`);
Expand All @@ -47,7 +48,8 @@ export function AutoIncrementSimple(
field.incrementBy = DEFAULT_INCREMENT;
}
}
schema.pre('save', function AutoIncrementPreSaveSimple() { // to have an name to the function if debugging
// to have an name to the function if debugging
schema.pre('save', function AutoIncrementPreSaveSimple() {
if (!this.isNew) {
logger.info('Starting to increment "%s"', (this.constructor as mongoose.Model<any>).modelName);
for (const field of fields) {
Expand All @@ -59,11 +61,14 @@ export function AutoIncrementSimple(
}

/** The Schema used for the trackers */
const IDSchema = new mongoose.Schema({
field: String,
model: String,
count: Number
}, { versionKey: false });
const IDSchema = new mongoose.Schema(
{
field: String,
model: String,
count: Number,
},
{ versionKey: false }
);
IDSchema.index({ field: 1, model: 1 }, { unique: true });

export const AutoIncrementIDSkipSymbol = Symbol('AutoIncrementIDSkip');
Expand All @@ -82,7 +87,7 @@ export function AutoIncrementID(schema: mongoose.Schema<any>, options: AutoIncre
trackerCollection: 'identitycounters',
trackerModelName: 'identitycounter',
startAt: 0,
...options
...options,
};

// check if the field is an number
Expand All @@ -106,11 +111,12 @@ export function AutoIncrementID(schema: mongoose.Schema<any>, options: AutoIncre
model = db.model(opt.trackerModelName, IDSchema, opt.trackerCollection);
// test if the counter document already exists
const counter = await model.findOne({ model: modelName, field: opt.field }).lean().exec();

if (!counter) {
await model.create({
model: modelName,
field: opt.field,
count: opt.startAt - opt.incrementBy
count: opt.startAt - opt.incrementBy,
} as AutoIncrementIDTrackerSpec);
}
}
Expand All @@ -127,17 +133,24 @@ export function AutoIncrementID(schema: mongoose.Schema<any>, options: AutoIncre
return;
}

const { count }: { count: number; } = await model.findOneAndUpdate({
field: opt.field,
model: modelName
} as AutoIncrementIDTrackerSpec, {
$inc: { count: opt.incrementBy }
}, {
new: true,
fields: { count: 1, _id: 0 },
upsert: true,
setDefaultsOnInsert: true
}).lean().exec();
const { count }: { count: number } = await model
.findOneAndUpdate(
{
field: opt.field,
model: modelName,
} as AutoIncrementIDTrackerSpec,
{
$inc: { count: opt.incrementBy },
},
{
new: true,
fields: { count: 1, _id: 0 },
upsert: true,
setDefaultsOnInsert: true,
}
)
.lean()
.exec();

logger.info('Setting "%s" to "%d"', opt.field, count);
this[opt.field] = count;
Expand Down
1 change: 1 addition & 0 deletions src/logSettings.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as log from 'loglevel';

export { log as logger };

export const setLogLevel = log.setLevel;
Expand Down
14 changes: 7 additions & 7 deletions test/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ describe('Basic Suite', () => {
describe('AutoIncrementSimple', () => {
it('Basic Function Mongoose', async () => {
const schema = new mongoose.Schema({
somefield: Number
somefield: Number,
});
schema.plugin(AutoIncrementSimple, [{ field: 'somefield' }]);
const model = mongoose.model('AutoIncrementSimple-SomeModel', schema);

const doc: mongoose.Document & { somefield: number; } = await model.create({ somefield: 10 }) as any;
const doc: mongoose.Document & { somefield: number } = (await model.create({ somefield: 10 })) as any;
expect(doc.somefield).toBe(10);

await doc.save();
Expand Down Expand Up @@ -49,12 +49,12 @@ describe('Basic Suite', () => {
it('Basic Function Mongoose', async () => {
const schema = new mongoose.Schema({
_id: Number,
somefield: Number
somefield: Number,
});
schema.plugin(AutoIncrementID, {});
const model = mongoose.model('AutoIncrementID-SomeModel', schema);

const doc: mongoose.Document & { somefield: number; } = await model.create({ somefield: 10 }) as any;
const doc: mongoose.Document & { somefield: number } = (await model.create({ somefield: 10 })) as any;
expect(doc.somefield).toBe(10);
expect(doc._id).toBe(0);

Expand Down Expand Up @@ -92,12 +92,12 @@ describe('Basic Suite', () => {
it('Basic Function Mongoose With startAt', async () => {
const schema = new mongoose.Schema({
_id: Number,
somefield: Number
somefield: Number,
});
schema.plugin(AutoIncrementID, { startAt: 2 });
const model = mongoose.model('AutoIncrementID-SomeModelStartAt', schema);

const doc: mongoose.Document & { somefield: number; } = await model.create({ somefield: 10 }) as any;
const doc: mongoose.Document & { somefield: number } = (await model.create({ somefield: 10 })) as any;
expect(doc.somefield).toBe(10);
expect(doc._id).toBe(2);

Expand Down Expand Up @@ -171,7 +171,7 @@ describe('Errors', () => {

it('should Error if the schema path is not an number', () => {
const schema = new mongoose.Schema({
nonNumberField: String
nonNumberField: String,
});
expect(() => schema.plugin(AutoIncrementSimple, { field: 'nonNumberField' })).toThrow(Error);
});
Expand Down
24 changes: 14 additions & 10 deletions test/utils/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,29 +18,27 @@ enum EConfig {
MONGODB_IP = 'MongoDB IP is not specified!',
MONGODB_DB = 'MongoDB DataBase is not specified!',
MONGODB_PORT = 'MongoDB Port is not specified!',
MONGODB_AUTH = 'You should activate & use MongoDB Authentication!'
MONGODB_AUTH = 'You should activate & use MongoDB Authentication!',
}

const env: NodeJS.ProcessEnv = process.env; // just to write less

let path: string = env.CONFIG ?? './test/config.json';
path = fs.existsSync(path) ? path : './test/config_default.json';

const configRAW: Readonly<IConfig> =
JSON.parse(fs.readFileSync(path).toString());
const configRAW: Readonly<IConfig> = JSON.parse(fs.readFileSync(path).toString());

// ENV || CONFIG-FILE || DEFAULT
const configFINAL: Readonly<IConfig> = {
Memory: env.C_USE_IN_MEMORY !== undefined ||
(typeof configRAW.Memory === 'boolean' ? configRAW.Memory : true),
Memory: env.C_USE_IN_MEMORY !== undefined || (typeof configRAW.Memory === 'boolean' ? configRAW.Memory : true),
DataBase: env.C_DATABASE ?? configRAW?.DataBase ?? 'typegooseTest',
Port: parseInt(env.C_PORT as string, 10) || configRAW.Port || 27017,
Auth: {
User: env.C_AUTH_USER ?? configRAW?.Auth?.User ?? '',
Passwd: env.C_AUTH_PASSWD || configRAW?.Auth?.Passwd || '',
DB: env.C_AUTH_DB || configRAW?.Auth?.DB || ''
DB: env.C_AUTH_DB || configRAW?.Auth?.DB || '',
},
IP: env.C_IP ?? configRAW.IP ?? 'localhost'
IP: env.C_IP ?? configRAW.IP ?? 'localhost',
};

/** Small callback for the tests below */
Expand All @@ -51,9 +49,15 @@ function cb(text: string): void {
}

if (!configFINAL.Memory) {
if (!configFINAL.IP) { cb(EConfig.MONGODB_IP); }
if (!configFINAL.DataBase) { cb(EConfig.MONGODB_DB); }
if (!configFINAL.Port) { cb(EConfig.MONGODB_PORT); }
if (!configFINAL.IP) {
cb(EConfig.MONGODB_IP);
}
if (!configFINAL.DataBase) {
cb(EConfig.MONGODB_DB);
}
if (!configFINAL.Port) {
cb(EConfig.MONGODB_PORT);
}
}

export { configFINAL as config };
9 changes: 6 additions & 3 deletions test/utils/mongooseConnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const staticOptions = {
useFindAndModify: false,
useCreateIndex: true,
useUnifiedTopology: true,
autoIndex: true
autoIndex: true,
} as mongoose.ConnectionOptions;

/**
Expand All @@ -44,11 +44,12 @@ export async function connect(extraConfig: ExtraConnectionConfig = {}): Promise<
} else {
// use external already running database
const options = Object.assign({}, staticOptions);

if (config?.Auth?.User?.length > 0) {
Object.assign(options, {
user: config.Auth.User,
pass: config.Auth.Passwd,
authSource: config.Auth.DB
authSource: config.Auth.DB,
});
}

Expand All @@ -75,6 +76,7 @@ export async function connect(extraConfig: ExtraConnectionConfig = {}): Promise<
*/
export async function disconnect(): Promise<void> {
await mongoose.disconnect();

if (config.Memory || !isNullOrUndefined(instance)) {
await instance.stop();
}
Expand All @@ -89,7 +91,8 @@ async function firstConnect() {
isFirst = false;
await mongoose.connection.db.dropDatabase(); // to always have a clean database

await Promise.all( // recreate the indexes that were dropped
await Promise.all(
// recreate the indexes that were dropped
Object.keys(mongoose.models).map(async (modelName) => {
await mongoose.models[modelName].ensureIndexes();
})
Expand Down

0 comments on commit ab98557

Please sign in to comment.