Skip to content

Commit

Permalink
Merge pull request #57 from Rocketseat/feat/test-and-provider-improve…
Browse files Browse the repository at this point in the history
…ments

feat: Add test and provider improvements
  • Loading branch information
fhugoduarte committed Jan 22, 2021
2 parents 70e41ae + 69d3358 commit 4355961
Show file tree
Hide file tree
Showing 9 changed files with 237 additions and 58 deletions.
12 changes: 12 additions & 0 deletions .nycrc
@@ -0,0 +1,12 @@
{
"all": true,
"include": [
"providers/**/*.ts",
"src/**/*.ts"
],
"exclude": [
"src/BullExceptionHandler.ts",
"**/*.spec.js",
"**/*.spec.ts"
]
}
3 changes: 1 addition & 2 deletions README.md
Expand Up @@ -175,8 +175,7 @@ export default class UserRegisterEmail implements JobContract {

public concurrency = 1

public connection = 'local'
...
...
}
```

Expand Down
12 changes: 12 additions & 0 deletions adonis-typings/bull.ts
Expand Up @@ -36,10 +36,22 @@ declare module '@ioc:Rocketseat/Bull' {
concurrency?: number;
handle: Processor;
boot?: (queue: Queue<T>) => void;
onCompleted?: (...args: any[]) => void
onProgress?: (...args: any[]) => void
onFailed?: (...args: any[]) => void
onWaiting?: (...args: any[]) => void
onDelayed?: (...args: any[]) => void
onStalled?: (...args: any[]) => void
onRemoved?: (...args: any[]) => void
onDrained?: (...args: any[]) => void
}

export interface EventListener { eventName: string; method: string }

export interface QueueContract<T = any> extends JobContract<T> {
bull: Queue<T>;
listeners: EventListener[];
instance: JobContract<T>;
}

export interface BullManagerContract {
Expand Down
29 changes: 28 additions & 1 deletion src/BullManager.ts
@@ -1,11 +1,14 @@
import { IocContract } from '@adonisjs/fold'
import { LoggerContract } from '@ioc:Adonis/Core/Logger'

import {
BullManagerContract,
JobContract,
QueueContract,
BullConfig
BullConfig,
EventListener
} from '@ioc:Rocketseat/Bull'

import {
Queue,
QueueScheduler,
Expand Down Expand Up @@ -35,17 +38,22 @@ export class BullManager implements BullManagerContract {

this._queues = this.jobs.reduce((queues, path) => {
const jobDefinition: JobContract = this.container.make(path)

const queueConfig = {
connection: this.config.connections[this.config.connection],
...jobDefinition.queueOptions
}

const jobListeners = this._getEventListener(jobDefinition)

// eslint-disable-next-line no-new
new QueueScheduler(jobDefinition.key, queueConfig)

queues[jobDefinition.key] = Object.freeze({
bull: new Queue(jobDefinition.key, queueConfig),
...jobDefinition,
instance: jobDefinition,
listeners: jobListeners,
handle: jobDefinition.handle,
boot: jobDefinition.boot
})
Expand All @@ -56,6 +64,20 @@ export class BullManager implements BullManagerContract {
return this.queues
}

private _getEventListener (job: JobContract): EventListener[] {
const jobListeners = Object.getOwnPropertyNames(Object.getPrototypeOf(job)).reduce((events, method: string) => {
if (method.startsWith('on')) {
const eventName = method.replace(/^on(\w)/, (_, group) => group.toLowerCase()).replace(/([A-Z]+)/, (_, group) => ` ${group.toLowerCase()}`)

events.push({ eventName, method })
}

return events
}, [] as EventListener[])

return jobListeners
}

public getByKey (key: string): QueueContract {
return this.queues[key]
}
Expand Down Expand Up @@ -88,6 +110,7 @@ export class BullManager implements BullManagerContract {
return job?.remove()
}

/* istanbul ignore next */
public ui (port = 9999) {
BullBoard.setQueues(
Object.keys(this.queues).map((key) => new BullBoard.BullMQAdapter(this.getByKey(key).bull))
Expand Down Expand Up @@ -133,6 +156,10 @@ export class BullManager implements BullManagerContract {

const worker = new Worker(key, processor, workerOptions)

jobDefinition.listeners.forEach(function (item) {
worker.on(item.eventName, jobDefinition.instance[item.method].bind(jobDefinition.instance))
})

const shutdown = () =>
Promise.all([jobDefinition.bull.close(), worker.close()])

Expand Down
64 changes: 40 additions & 24 deletions test-helpers/index.ts
Expand Up @@ -2,9 +2,21 @@ import { join } from 'path'
import { Filesystem } from '@poppinss/dev-utils'
import { Application } from '@adonisjs/core/build/standalone'

export const fs = new Filesystem(join(__dirname, '__app'))
import { FakeLogger } from '@adonisjs/logger/build/standalone'

export async function setupApplication (additionalProviders?: string[], environment: 'web' | 'repl' | 'test' = 'test') {
export const fs = new Filesystem(join(__dirname, 'app'))

export class MyFakeLogger extends FakeLogger {
constructor (public assert, config, pino?) {
super(config, pino)
}

error (message: string) {
this.assert.isTrue(message.includes('name=TestBull-name id='))
}
}

export async function setupApplication (environment: 'web' | 'repl' | 'test' = 'test') {
await fs.add('.env', '')

await fs.add(
Expand All @@ -18,44 +30,48 @@ export async function setupApplication (additionalProviders?: string[], environm
`
)

await fs.add('contracts/bull.ts',
`
declare module '@ioc:Rocketseat/Bull' {
interface BullConnectionsList {
local: BullConnectionContract;
}
}
`)
await fs.add('app/Jobs/SomeJob.ts',
`
export default class SomeJob {
public key = 'SomeJob-key'
public async handle () {
return 'good luck'
}
}
`)

await fs.add('start/jobs.ts',
`
export default ['App/SomeJob']
`)

await fs.add('config/bull.ts',
`
import Env from '@ioc:Adonis/Core/Env'
import { BullConfig } from '@ioc:Rocketseat/Bull'
const bullConfig: BullConfig = {
connection: Env.get('BULL_CONNECTION'),
const bullConfig = {
connection: 'local',
connections: {
local: {
host: Env.get('REDIS_HOST'),
port: Env.get('REDIS_PORT'),
password: Env.get('REDIS_PASSWORD', ''),
db: 0,
keyPrefix: '',
host: 'localhost',
port: 6379,
password: '',
db: 0,
keyPrefix: '',
},
},
}
} as unknown as BullConfig
export default bullConfig
`)

const app = new Application(fs.basePath, environment, {
aliases: {
App: './app'
},
providers: [
'@adonisjs/core'
].concat(additionalProviders || [])
'@adonisjs/core',
'../../providers/BullProvider'
]
})

app.setup()
Expand Down
7 changes: 0 additions & 7 deletions test/functional/app/Jobs/SomeJob.ts

This file was deleted.

5 changes: 2 additions & 3 deletions test/functional/providers.spec.ts
@@ -1,5 +1,3 @@
/// <reference path="../../adonis-typings/bull.ts" />

import test from 'japa'
import { fs, setupApplication } from '../../test-helpers'
import { BullManager } from '../../src/BullManager'
Expand All @@ -10,7 +8,8 @@ test.group('Bull Provider', (group) => {
})

test('register bull provider', async (assert) => {
const app = await setupApplication(['../../providers/BullProvider'])
const app = await setupApplication()

assert.instanceOf(app.container.use('Rocketseat/Bull'), BullManager)
})
})
1 change: 0 additions & 1 deletion test/functional/start/jobs.ts

This file was deleted.

0 comments on commit 4355961

Please sign in to comment.