Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: upgrade strict-event-emitter to 0.5.0 #278

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
"md5": "^2.3.0",
"outvariant": "^1.2.1",
"pluralize": "^8.0.0",
"strict-event-emitter": "^0.2.0",
"strict-event-emitter": "^0.5.0",
"uuid": "^8.3.1"
},
"optionalDependencies": {
Expand All @@ -65,4 +65,4 @@
"path": "./node_modules/cz-conventional-changelog"
}
}
}
}
57 changes: 26 additions & 31 deletions src/db/Database.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import md5 from 'md5'
import { invariant } from 'outvariant'
import { StrictEventEmitter } from 'strict-event-emitter'
import { Emitter } from 'strict-event-emitter'
import {
Entity,
ENTITY_TYPE,
Expand All @@ -27,40 +27,31 @@ export interface SerializedEntity extends Entity<any, any> {
[SERIALIZED_INTERNAL_PROPERTIES_KEY]: SerializedInternalEntityProperties
}

export type DatabaseMethodToEventFn<ArgsType extends unknown[]> = (
sourceId: string,
args: ArgsType,
) => void

export interface DatabaseEventsMap {
create: DatabaseMethodToEventFn<
[
modelName: KeyType,
entity: SerializedEntity,
customPrimaryKey?: PrimaryKeyType,
]
>
update: DatabaseMethodToEventFn<
[
modelName: KeyType,
prevEntity: SerializedEntity,
nextEntity: SerializedEntity,
]
>
delete: DatabaseMethodToEventFn<
[modelName: KeyType, primaryKey: PrimaryKeyType]
>
export type DatabaseEventsMap = {
create: [
sourceId: string,
modelName: KeyType,
entity: SerializedEntity,
customPrimaryKey?: PrimaryKeyType,
]
update: [
sourceId: string,
modelName: KeyType,
prevEntity: SerializedEntity,
nextEntity: SerializedEntity,
]
delete: [sourceId: string, modelName: KeyType, primaryKey: PrimaryKeyType]
}

let callOrder = 0

export class Database<Dictionary extends ModelDictionary> {
public id: string
public events: StrictEventEmitter<DatabaseEventsMap>
public events: Emitter<DatabaseEventsMap>
private models: Models<Dictionary>

constructor(dictionary: Dictionary) {
this.events = new StrictEventEmitter()
this.events = new Emitter()
this.models = Object.keys(dictionary).reduce<Models<Dictionary>>(
(acc, modelName: keyof Dictionary) => {
acc[modelName] = new Map<string, Entity<Dictionary, string>>()
Expand Down Expand Up @@ -120,11 +111,13 @@ export class Database<Dictionary extends ModelDictionary> {
const primaryKey =
customPrimaryKey || (entity[entity[PRIMARY_KEY]] as string)

this.events.emit('create', this.id, [
this.events.emit(
'create',
this.id,
modelName,
this.serializeEntity(entity),
customPrimaryKey,
])
)
return this.getModel(modelName).set(primaryKey, entity)
}

Expand All @@ -143,19 +136,21 @@ export class Database<Dictionary extends ModelDictionary> {
this.getModel(modelName).set(nextPrimaryKey, nextEntity)

// this.create(modelName, nextEntity, nextPrimaryKey)
this.events.emit('update', this.id, [
this.events.emit(
'update',
this.id,
modelName,
this.serializeEntity(prevEntity),
this.serializeEntity(nextEntity),
])
)
}

delete<ModelName extends keyof Dictionary>(
modelName: ModelName,
primaryKey: PrimaryKeyType,
): void {
this.getModel(modelName).delete(primaryKey)
this.events.emit('delete', this.id, [modelName, primaryKey])
this.events.emit('delete', this.id, modelName, primaryKey)
}

has<ModelName extends keyof Dictionary>(
Expand Down
23 changes: 14 additions & 9 deletions src/extensions/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,29 @@ import {
SERIALIZED_INTERNAL_PROPERTIES_KEY,
} from '../db/Database'
import { inheritInternalProperties } from '../utils/inheritInternalProperties'
import { Listener } from 'strict-event-emitter'

export type DatabaseMessageEventData =
| {
operationType: 'create'
payload: Parameters<DatabaseEventsMap['create']>
payload: DatabaseEventsMap['create']
}
| {
operationType: 'update'
payload: Parameters<DatabaseEventsMap['update']>
payload: DatabaseEventsMap['update']
}
| {
operationType: 'delete'
payload: Parameters<DatabaseEventsMap['delete']>
payload: DatabaseEventsMap['delete']
}

function removeListeners<Event extends keyof DatabaseEventsMap>(
event: Event,
db: Database<any>,
) {
const listeners = db.events.listeners(event) as DatabaseEventsMap[Event][]
const listeners = db.events.listeners(event) as Listener<
DatabaseEventsMap[Event]
>[]

listeners.forEach((listener) => {
db.events.removeListener(event, listener)
Expand Down Expand Up @@ -90,13 +93,13 @@ export function sync(db: Database<any>) {
// to the current database instance.
switch (event.data.operationType) {
case 'create': {
const [modelName, entity, customPrimaryKey] = event.data.payload[1]
const [_, modelName, entity, customPrimaryKey] = event.data.payload
db.create(modelName, deserializeEntity(entity), customPrimaryKey)
break
}

case 'update': {
const [modelName, prevEntity, nextEntity] = event.data.payload[1]
const [_, modelName, prevEntity, nextEntity] = event.data.payload
db.update(
modelName,
deserializeEntity(prevEntity),
Expand All @@ -105,8 +108,10 @@ export function sync(db: Database<any>) {
break
}

default: {
db[event.data.operationType](...event.data.payload[1])
case 'delete': {
const [_, modelName, primaryKey] = event.data.payload
db.delete(modelName, primaryKey)
break
}
}

Expand All @@ -120,7 +125,7 @@ export function sync(db: Database<any>) {
function broadcastDatabaseEvent<Event extends keyof DatabaseEventsMap>(
operationType: Event,
) {
return (...payload: Parameters<DatabaseEventsMap[Event]>) => {
return (...payload: DatabaseEventsMap[Event]) => {
channel.postMessage({
operationType,
payload,
Expand Down
6 changes: 5 additions & 1 deletion src/model/generateGraphQLHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,11 @@ function createComparatorGraphQLInputType(
name,
fields: Object.keys(comparators).reduce<GraphQLInputFieldConfigMap>(
(fields, comparatorFn) => {
const fieldType = ['between', 'notBetween', 'in', 'notIn'].includes(comparatorFn) ? new GraphQLList(type) : type
const fieldType = ['between', 'notBetween', 'in', 'notIn'].includes(
comparatorFn,
)
? new GraphQLList(type)
: type
fields[comparatorFn] = { type: fieldType }
return fields
},
Expand Down
5 changes: 4 additions & 1 deletion src/model/generateRestHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ type RequestParams<Key extends PrimaryKeyType> = {
export function createUrlBuilder(baseUrl?: string) {
return (path: string) => {
// For the previous implementation trailing slash didn't matter, we must keep it this way for backward compatibility
const normalizedBaseUrl = baseUrl && baseUrl.slice(-1) === '/' ? baseUrl.slice(0, -1) : baseUrl || '';
const normalizedBaseUrl =
baseUrl && baseUrl.slice(-1) === '/'
? baseUrl.slice(0, -1)
: baseUrl || ''
return `${normalizedBaseUrl}/${path}`
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils/iteratorUtils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PrimaryKeyType } from "../glossary"
import { PrimaryKeyType } from '../glossary'

export function forEach<K extends PrimaryKeyType, V>(
fn: (key: K, value: V) => any,
Expand Down
6 changes: 3 additions & 3 deletions test/db/events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ test('emits the "create" event when a new entity is created', (done) => {
user: dictionary.user,
})

db.events.on('create', (id, [modelName, entity, primaryKey]) => {
db.events.on('create', (id, modelName, entity, primaryKey) => {
expect(id).toEqual(db.id)
expect(modelName).toEqual('user')
expect(entity).toEqual({
Expand Down Expand Up @@ -69,7 +69,7 @@ test('emits the "update" event when an existing entity is updated', (done) => {
user: dictionary.user,
})

db.events.on('update', (id, [modelName, prevEntity, nextEntity]) => {
db.events.on('update', (id, modelName, prevEntity, nextEntity) => {
expect(id).toEqual(db.id)
expect(modelName).toEqual('user')
expect(prevEntity).toEqual({
Expand Down Expand Up @@ -133,7 +133,7 @@ test('emits the "delete" event when an existing entity is deleted', (done) => {
user: dictionary.user,
})

db.events.on('delete', (id, [modelName, primaryKey]) => {
db.events.on('delete', (id, modelName, primaryKey) => {
expect(id).toEqual(db.id)
expect(modelName).toEqual('user')
expect(primaryKey).toEqual('abc-123')
Expand Down
7 changes: 6 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -814,7 +814,7 @@
resolved "https://registry.yarnpkg.com/@types/cookie/-/cookie-0.4.1.tgz#bfd02c1f2224567676c1545199f87c3a861d878d"
integrity sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==

"@types/debug@^4.1.5", "@types/debug@^4.1.7":
"@types/debug@^4.1.7":
version "4.1.7"
resolved "https://registry.yarnpkg.com/@types/debug/-/debug-4.1.7.tgz#7cc0ea761509124709b8b2d1090d8f6c17aadb82"
integrity sha512-9AonUzyTjXXhEOa0DnqpzZi6VHlqKMswga9EXjpXnnqxwLtdvPPtlO8evrI5D9S6asFRCQ6v+wpiUKbw+vKqyg==
Expand Down Expand Up @@ -5475,6 +5475,11 @@ strict-event-emitter@^0.2.0:
dependencies:
events "^3.3.0"

strict-event-emitter@^0.5.0:
version "0.5.0"
resolved "https://registry.yarnpkg.com/strict-event-emitter/-/strict-event-emitter-0.5.0.tgz#a4aa84a3d9b4a9be12e750a75e089cabb3dbc0e2"
integrity sha512-sqnMpVJLSB3daNO6FcvsEk4Mq5IJeAwDeH80DP1S8+pgxrF6yZnE1+VeapesGled7nEcIkz1Ax87HzaIy+02kA==

string-length@^4.0.1:
version "4.0.2"
resolved "https://registry.yarnpkg.com/string-length/-/string-length-4.0.2.tgz#a8a8dc7bd5c1a82b9b3c8b87e125f66871b6e57a"
Expand Down