Skip to content

Commit cae6036

Browse files
committed
Consistently use assert
1 parent 6d88bba commit cae6036

9 files changed

Lines changed: 37 additions & 59 deletions

File tree

src/EventStore.js

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -397,11 +397,7 @@ class EventStore extends events.EventEmitter {
397397
condition.raw
398398
);
399399

400-
if (stream.next() !== false) {
401-
throw new OptimisticConcurrencyError(
402-
`Optimistic Concurrency error. A conflicting event was committed since the condition was obtained.`
403-
);
404-
}
400+
assert(stream.next() === false, `Optimistic Concurrency error. A conflicting event was committed since the condition was obtained.`, OptimisticConcurrencyError);
405401
}
406402

407403
/**
@@ -470,9 +466,10 @@ class EventStore extends events.EventEmitter {
470466
}
471467
assert(!this.streams[streamName].closed, `Stream "${streamName}" is closed and cannot be written to.`);
472468
let streamVersion = this.streams[streamName].index.length;
473-
if (expectedVersion !== ExpectedVersion.Any && streamVersion !== expectedVersion) {
474-
throw new OptimisticConcurrencyError(`Optimistic Concurrency error. Expected stream "${streamName}" at version ${expectedVersion} but is at version ${streamVersion}.`);
475-
}
469+
assert(expectedVersion === ExpectedVersion.Any || streamVersion === expectedVersion,
470+
`Optimistic Concurrency error. Expected stream "${streamName}" at version ${expectedVersion} but is at version ${streamVersion}.`,
471+
OptimisticConcurrencyError
472+
);
476473

477474
if (events.length > 1) {
478475
delete metadata.commitVersion;
@@ -550,14 +547,12 @@ class EventStore extends events.EventEmitter {
550547
const queryTypes = [];
551548
for (const type of types) {
552549
if (!(type in this.streams)) {
553-
if (this.typeAccessor) {
554-
// typeAccessor is configured: type streams are created on commit, so a missing
555-
// stream simply means no event of this type has been committed yet — treat as empty.
556-
continue;
557-
}
558550
// No typeAccessor: the stream was never created; we cannot know whether events of
559551
// this type exist in the store, so throw to avoid an unintentional full-store scan.
560-
throw new Error(`Type stream "${type}" does not exist. Create it with createEventStream() first, or configure typeAccessor to have type streams created automatically on commit.`);
552+
assert(!!this.typeAccessor, `Type stream "${type}" does not exist. Create it with createEventStream() first, or configure typeAccessor to have type streams created automatically on commit.`);
553+
// typeAccessor is configured: type streams are created on commit, so a missing
554+
// stream simply means no event of this type has been committed yet — treat as empty.
555+
continue;
561556
}
562557
queryTypes.push(type);
563558
}
@@ -675,9 +670,8 @@ class EventStore extends events.EventEmitter {
675670
streamName.startsWith(categoryName + '/')
676671
);
677672

678-
if (categoryStreams.length === 0) {
679-
throw new Error(`No streams for category '${categoryName}' exist.`);
680-
}
673+
assert(categoryStreams.length > 0, `No streams for category '${categoryName}' exist.`);
674+
681675
return this.fromStreams(categoryName, categoryStreams, minRevision, maxRevision, predicate, raw);
682676
}
683677

src/Index/ReadableIndex.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -214,8 +214,8 @@ class ReadableIndex extends events.EventEmitter {
214214
fs.readSync(this.fd, headerBuffer, 0, 8 + 4, 0);
215215
const headerMagic = headerBuffer.toString('utf8', 0, 8);
216216

217-
assert(headerMagic.substr(0, 6) === HEADER_MAGIC.substr(0, 6), 'Invalid file header.');
218-
assert(headerMagic === HEADER_MAGIC, `Invalid file version. The index ${this.fileName} was created with a different library version (${headerMagic.substr(6)}).`);
217+
assert(headerMagic.substring(0, 6) === HEADER_MAGIC.substring(0, 6), 'Invalid file header.');
218+
assert(headerMagic === HEADER_MAGIC, `Invalid file version. The index ${this.fileName} was created with a different library version (${headerMagic.substring(6)}).`);
219219

220220
const metadataSize = headerBuffer.readUInt32BE(8);
221221
assert(metadataSize >= 3, 'Invalid metadata size.');

src/Index/WritableIndex.js

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import fs from 'fs';
22
import ReadableIndex, { Entry, CorruptedIndexError, HEADER_MAGIC } from './ReadableIndex.js';
3-
import { assertEqual } from '../util.js';
3+
import { assert, assertEqual } from '../util.js';
44
import { buildMetadataHeader } from '../metadataUtil.js';
55
import { ensureDirectory } from '../fsUtil.js';
66

@@ -191,9 +191,7 @@ class WritableIndex extends ReadableIndex {
191191
assertEqual(entry.constructor.size, this.EntryClass.size, `Invalid entry size.`);
192192

193193
const dataLen = this.data.length;
194-
if (dataLen > 0 && this.data[dataLen - 1].number >= entry.number) {
195-
throw new Error('Consistency error. Tried to add an index that should come before existing last entry.');
196-
}
194+
assert(dataLen === 0 || this.data.at(-1).number < entry.number, 'Consistency error. Tried to add an index that should come before existing last entry.');
197195

198196
if (this.readUntil === dataLen - 1) {
199197
this.readUntil++;

src/JoinEventStream.js

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import EventStream from './EventStream.js';
2-
import { kWayMerge } from './util.js';
2+
import {assert, kWayMerge} from './util.js';
33

44
/** Reusable sentinel used for missing or empty per-stream iterators. */
55
const emptyIterator = Object.freeze({ next() { return { done: true }; } });
@@ -32,9 +32,7 @@ class JoinEventStream extends EventStream {
3232
*/
3333
constructor(name, streams, eventStore, minRevision = 1, maxRevision = -1, predicate = null, raw = false) {
3434
super(name, eventStore, minRevision, maxRevision, predicate, raw);
35-
if (!(streams instanceof Array) || streams.length === 0) {
36-
throw new Error(`Invalid list of streams supplied to JoinStream ${name}.`);
37-
}
35+
assert(streams instanceof Array && streams.length > 0, `Invalid list of streams supplied to JoinStream ${name}.`);
3836

3937
this.streamIndex = eventStore.storage.index;
4038
// Translate revisions to index numbers (1-based) and wrap around negatives

src/Partition/ReadablePartition.js

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -116,10 +116,10 @@ class ReadablePartition extends events.EventEmitter {
116116
fs.readSync(this.fd, headerBuffer, 0, 8 + 4, 0);
117117
const headerMagic = headerBuffer.toString('utf8', 0, 8);
118118

119-
assert(headerMagic.substr(0, 6) === HEADER_MAGIC.substr(0, 6), `Invalid file header in partition ${this.name}.`);
119+
assert(headerMagic.substring(0, 6) === HEADER_MAGIC.substring(0, 6), `Invalid file header in partition ${this.name}.`);
120120

121121
this.header = headerMagic;
122-
assert(headerMagic === HEADER_MAGIC, `Invalid file version. The partition ${this.name} was created with a different library version (${headerMagic.substr(6)}).`);
122+
assert(headerMagic === HEADER_MAGIC, `Invalid file version. The partition ${this.name} was created with a different library version (${headerMagic.substring(6)}).`);
123123

124124
const metadataSize = headerBuffer.readUInt32BE(8);
125125
assert(metadataSize > 2 && metadataSize <= 4096, 'Invalid metadata size.');
@@ -202,9 +202,7 @@ class ReadablePartition extends events.EventEmitter {
202202
const dataSize = buffer.readUInt32BE(offset + 0);
203203
assert(dataSize > 0 && dataSize <= 64 * 1024 * 1024, `Error reading document size from ${position}, got ${dataSize}.`);
204204

205-
if (size && dataSize !== size) {
206-
throw new InvalidDataSizeError(`Invalid document size ${dataSize} at position ${position}, expected ${size}.`);
207-
}
205+
assert(!size || dataSize === size, `Invalid document size ${dataSize} at position ${position}, expected ${size}.`, InvalidDataSizeError);
208206

209207
const sequenceNumber = buffer.readUInt32BE(offset + 4);
210208
const time64 = buffer.readDoubleBE(offset + 8);
@@ -253,9 +251,7 @@ class ReadablePartition extends events.EventEmitter {
253251
}
254252

255253
const writeSize = this.documentWriteSize(dataSize);
256-
if (position + writeSize > this.size) {
257-
throw new CorruptFileError(`Invalid document at position ${position}. This may be caused by an unfinished write.`);
258-
}
254+
assert(position + writeSize <= this.size, `Invalid document at position ${position}. This may be caused by an unfinished write.`, CorruptFileError);
259255

260256
if (dataSize + DOCUMENT_HEADER_SIZE > reader.buffer.byteLength) {
261257
const tempReadBuffer = Buffer.allocUnsafe(dataSize);

src/Partition/WritablePartition.js

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -184,9 +184,8 @@ class WritablePartition extends ReadablePartition {
184184
time64 = this.clock.time();
185185
}
186186
/* istanbul ignore if */
187-
if (time64 < 0) {
188-
throw new Error('Time may not be negative!');
189-
}
187+
assert(time64 >= 0, 'Time may not be negative!');
188+
190189
buffer.writeUInt32BE(dataSize, offset);
191190
buffer.writeUInt32BE(sequenceNumber, offset + 4);
192191
buffer.writeDoubleBE(time64, offset + 8);
@@ -210,7 +209,7 @@ class WritablePartition extends ReadablePartition {
210209
bytesWritten += fs.writeSync(this.fd, this.writeMetaBuffer, 0, DOCUMENT_HEADER_SIZE);
211210
bytesWritten += fs.writeSync(this.fd, data);
212211
const padSize = alignTo(dataSize + DOCUMENT_FOOTER_SIZE, DOCUMENT_ALIGNMENT);
213-
bytesWritten += fs.writeSync(this.fd, DOCUMENT_PAD.substr(0, padSize));
212+
bytesWritten += fs.writeSync(this.fd, DOCUMENT_PAD.substring(0, padSize));
214213
this.writeMetaBuffer.writeUInt32BE(dataSize, 0);
215214
bytesWritten += fs.writeSync(this.fd, this.writeMetaBuffer, 0, 4);
216215
bytesWritten += fs.writeSync(this.fd, DOCUMENT_SEPARATOR);
@@ -237,7 +236,7 @@ class WritablePartition extends ReadablePartition {
237236
bytesWritten += this.writeDocumentHeader(this.writeBuffer, this.writeBufferCursor, dataSize, sequenceNumber);
238237
bytesWritten += this.writeBuffer.write(data, this.writeBufferCursor + bytesWritten, 'utf8');
239238
const padSize = alignTo(dataSize + DOCUMENT_FOOTER_SIZE, DOCUMENT_ALIGNMENT);
240-
bytesWritten += this.writeBuffer.write(DOCUMENT_PAD.substr(0, padSize), this.writeBufferCursor + bytesWritten, 'utf8');
239+
bytesWritten += this.writeBuffer.write(DOCUMENT_PAD.substring(0, padSize), this.writeBufferCursor + bytesWritten, 'utf8');
241240
this.writeBuffer.writeUInt32BE(dataSize, this.writeBufferCursor + bytesWritten);
242241
bytesWritten += 4;
243242
bytesWritten += this.writeBuffer.write(DOCUMENT_SEPARATOR, this.writeBufferCursor + bytesWritten, 'utf8');
@@ -390,9 +389,7 @@ class WritablePartition extends ReadablePartition {
390389
try {
391390
this.readFrom(after);
392391
} catch (e) {
393-
if (!(e instanceof CorruptFileError)) {
394-
throw new Error('Can only truncate on valid document boundaries.');
395-
}
392+
assert(e instanceof CorruptFileError, 'Can only truncate on valid document boundaries.');
396393
}
397394

398395
fs.truncateSync(this.fileName, this.headerSize + after);

src/Storage/ReadOnlyStorage.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ class ReadOnlyStorage extends ReadableStorage {
2323
* @returns {boolean}
2424
*/
2525
storageFilesFilter(filename) {
26-
return filename.substr(-7) !== '.branch' && filename.substr(0, this.storageFile.length) === this.storageFile;
26+
return !filename.endsWith('.branch') && filename.substring(0, this.storageFile.length) === this.storageFile;
2727
}
2828

2929
/**
@@ -46,8 +46,8 @@ class ReadOnlyStorage extends ReadableStorage {
4646
* @param {string} filename
4747
*/
4848
onStorageFileChanged(filename) {
49-
if (filename.substr(-6) === '.index') {
50-
const indexName = filename.substr(this.storageFile.length + 1, filename.length - this.storageFile.length - 7);
49+
if (filename.endsWith('.index')) {
50+
const indexName = filename.substring(this.storageFile.length + 1, filename.length - 6);
5151
// New indexes are not automatically opened in the reader
5252
this.emit('index-created', indexName);
5353
return;

src/Storage/WritableStorage.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -232,9 +232,8 @@ class WritableStorage extends ReadableStorage {
232232
this.locked = true;
233233
} catch (e) {
234234
/* istanbul ignore if */
235-
if (e.code !== 'EEXIST') {
236-
throw new Error(`Error creating lock for storage ${this.storageFile}: ` + e.message);
237-
}
235+
assert(e.code === 'EEXIST', `Error creating lock for storage ${this.storageFile}: ` + e.message)
236+
238237
throw new StorageLockedError(`Storage ${this.storageFile} is locked by another process`);
239238
}
240239
return true;

src/metadataUtil.js

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import crypto from 'crypto';
2-
import { assertEqual } from './util.js';
2+
import {assert, assertEqual} from './util.js';
33

44
/**
55
* Build a buffer containing the file magic header and a JSON stringified metadata block, padded to be a multiple of 16 bytes long.
@@ -90,9 +90,8 @@ function buildMatcherFromMetadata(matcherMetadata, hmac) {
9090
if (typeof matcherMetadata.matcher === 'object') {
9191
matcher = matcherMetadata.matcher;
9292
} else {
93-
if (matcherMetadata.hmac !== hmac(matcherMetadata.matcher)) {
94-
throw new Error('Invalid HMAC for matcher.');
95-
}
93+
assert(matcherMetadata.hmac === hmac(matcherMetadata.matcher), 'Invalid HMAC for matcher.');
94+
9695
matcher = eval('(' + matcherMetadata.matcher + ')').bind({}); // jshint ignore:line
9796
}
9897
return matcher;
@@ -125,9 +124,7 @@ function buildTypeMatcherFn(payloadPath) {
125124
* @returns {function(Buffer): boolean}
126125
*/
127126
function buildRawBufferMatcher(matcher = {}) {
128-
if (!matcher || typeof matcher !== 'object' || Array.isArray(matcher)) {
129-
throw new TypeError('Matcher must be an object.');
130-
}
127+
assert(matcher && typeof matcher ==='object' && !Array.isArray(matcher), 'Matcher must be an object.', TypeError);
131128

132129
const root = buildMatcherTree(matcher);
133130
if (root.children.length === 0) {
@@ -179,9 +176,8 @@ function buildMatcherTree(matcher) {
179176
const child = { objectPattern: null, valuePatterns: null, node: null, objMatch: null, valueMatches: [] };
180177

181178
if (Array.isArray(value)) {
182-
if (value.some(item => item && typeof item === 'object')) {
183-
throw new TypeError('Array matcher values must be scalars.');
184-
}
179+
assert(!value.some(item => item && typeof item === 'object'), 'Array matcher values must be scalars.', TypeError);
180+
185181
child.valuePatterns = value.map(item => Buffer.concat([keyPrefix, Buffer.from(JSON.stringify(item), 'utf8')]));
186182
} else if (value && typeof value === 'object') {
187183
child.objectPattern = Buffer.concat([keyPrefix, Buffer.from('{', 'utf8')]);

0 commit comments

Comments
 (0)