Skip to content

Commit

Permalink
ESlint issues
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenwf committed Oct 19, 2021
1 parent 9ac80cf commit 3bcce27
Show file tree
Hide file tree
Showing 26 changed files with 138 additions and 140 deletions.
8 changes: 5 additions & 3 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
singleQuote: true
trailingComma: es5
printWidth: 120
{
"singleQuote": true,
"trailingComma": "es5",
"printWidth": 120
}
6 changes: 3 additions & 3 deletions __tests__/example.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { createApp } from '../src/app';
import { Worker } from 'bullmq';

beforeAll(async () => {
await global.setApp(baseConfig => createApp(baseConfig));
await global.setApp((baseConfig) => createApp(baseConfig));
});

describe('Creating and fetching a task', () => {
Expand Down Expand Up @@ -41,10 +41,10 @@ describe('Creating and fetching a task', () => {
test('Simple event', async () => {
expect.assertions(4);

const worker = new Promise<Worker>(resolve => {
const worker = new Promise<Worker>((resolve) => {
const _worker = new Worker(
'jest',
async job => {
async (job) => {
expect(job.name).toEqual('created');
expect(job.data.type).toEqual('task-type-a');
expect(job.data.context[0]).toEqual('urn:madoc:site:456');
Expand Down
2 changes: 1 addition & 1 deletion jest.environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import MockReq from 'mock-req';
// @ts-ignore
import MockRes from 'mock-res';
import compose from 'koa-compose';
import { AppConfig } from './dist/types';
import { AppConfig } from './src/types';
import { WorkerOptions } from 'bullmq';

type NewIncomingMessage = IncomingMessage & Transform;
Expand Down
4 changes: 2 additions & 2 deletions src/database/get-task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ export async function getTask(
`
);

const actualTask = taskList.find(t => t.id === id);
const subtasks = taskList.filter(t => t.id !== id);
const actualTask = taskList.find((t) => t.id === id);
const subtasks = taskList.filter((t) => t.id !== id);

if (!actualTask) {
throw new NotFound();
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ async function main() {
}
}

main().catch(err => {
main().catch((err) => {
console.error(err);
process.exit(1);
});
14 changes: 8 additions & 6 deletions src/middleware/db-connection.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Middleware } from 'koa';
import { DatabasePoolType } from 'slonik';

export const dbConnection = (pool: DatabasePoolType): Middleware => async (context, next) => {
await pool.connect(async connection => {
context.connection = connection;
await next();
});
};
export const dbConnection =
(pool: DatabasePoolType): Middleware =>
async (context, next) => {
await pool.connect(async (connection) => {
context.connection = connection;
await next();
});
};
138 changes: 68 additions & 70 deletions src/middleware/queue-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,87 +4,85 @@ function noop() {
// no-op
}

export const queueEvents = (
baseConfig?: BaseQueueConfig,
queueList: string[] = [],
enabled = true
): RouteMiddleware => async (context, next) => {
const dispatchConfig = baseConfig?.dispatch || ({} as any);
export const queueEvents =
(baseConfig?: BaseQueueConfig, queueList: string[] = [], enabled = true): RouteMiddleware =>
async (context, next) => {
const dispatchConfig = baseConfig?.dispatch || ({} as any);

context.state.queue = [];
context.state.queueList = queueList;
context.state.dispatch = !enabled
? noop
: (
task: { id: string; type: string; events?: string[] },
eventName: string,
subject?: string | number,
state: any = {}
) => {
// Non prefixed.
const eventsToFire = task.events;
context.state.queue = [];
context.state.queueList = queueList;
context.state.dispatch = !enabled
? noop
: (
task: { id: string; type: string; events?: string[] },
eventName: string,
subject?: string | number,
state: any = {}
) => {
// Non prefixed.
const eventsToFire = task.events;

if (!eventsToFire || eventsToFire.length === 0 || !task.events || task.events.length === 0) {
return;
}
if (!eventsToFire || eventsToFire.length === 0 || !task.events || task.events.length === 0) {
return;
}

const hasSubject = typeof subject !== 'undefined';
const queueMap: { [ev: string]: string[] } = {};
const allEvents: string[] = [];
for (const eventString of task.events) {
const [queueName, event, ...sub] = eventString.split('.');
const ev = `${event}${hasSubject ? `.${sub.join('.')}` : ''}`;
queueMap[ev] = queueMap[ev] ? queueMap[ev] : [];
queueMap[ev].push(queueName);
allEvents.push(ev);
}
const hasSubject = typeof subject !== 'undefined';
const queueMap: { [ev: string]: string[] } = {};
const allEvents: string[] = [];
for (const eventString of task.events) {
const [queueName, event, ...sub] = eventString.split('.');
const ev = `${event}${hasSubject ? `.${sub.join('.')}` : ''}`;
queueMap[ev] = queueMap[ev] ? queueMap[ev] : [];
queueMap[ev].push(queueName);
allEvents.push(ev);
}

// Push the event.
const realEvent = `${eventName}${hasSubject ? `.${subject}` : ''}`;
function push(queue_id: string) {
context.state.queue.push({
queue_id,
event: {
name: realEvent,
data: { subject, state, taskId: task.id, type: task.type, context: context.state.jwt.context },
opts: {
lifo: eventName !== 'created',
// Push the event.
const realEvent = `${eventName}${hasSubject ? `.${subject}` : ''}`;
function push(queue_id: string) {
context.state.queue.push({
queue_id,
event: {
name: realEvent,
data: { subject, state, taskId: task.id, type: task.type, context: context.state.jwt.context },
opts: {
lifo: eventName !== 'created',
},
},
},
});
}
});
}

if (allEvents.indexOf(realEvent) !== -1 && queueMap[realEvent]) {
for (const queue_id of queueMap[realEvent]) {
push(queue_id);
if (allEvents.indexOf(realEvent) !== -1 && queueMap[realEvent]) {
for (const queue_id of queueMap[realEvent]) {
push(queue_id);
}
}
}

if (dispatchConfig[eventName]?.length) {
for (const queue_id of dispatchConfig[eventName]) {
push(queue_id);
if (dispatchConfig[eventName]?.length) {
for (const queue_id of dispatchConfig[eventName]) {
push(queue_id);
}
}
}
};
};

await next();
await next();

// Only if there are events, and if there are queues.
if (context.state.queueList.length && context.state.queue.length && context.getQueue) {
const queues: { [key: string]: Array<{ name: string; data: any }> } = {};
// Only if there are events, and if there are queues.
if (context.state.queueList.length && context.state.queue.length && context.getQueue) {
const queues: { [key: string]: Array<{ name: string; data: any }> } = {};

context.state.queue.forEach(item => {
if (context.state.queueList.indexOf(item.queue_id) !== -1) {
queues[item.queue_id] = queues[item.queue_id] ? queues[item.queue_id] : [];
queues[item.queue_id].push(item.event);
}
});
context.state.queue.forEach((item) => {
if (context.state.queueList.indexOf(item.queue_id) !== -1) {
queues[item.queue_id] = queues[item.queue_id] ? queues[item.queue_id] : [];
queues[item.queue_id].push(item.event);
}
});

const queueIds = Object.keys(queues);
for (const queueId of queueIds) {
const queue = context.getQueue(queueId);
await queue.addBulk(queues[queueId]);
await queue.disconnect();
const queueIds = Object.keys(queues);
for (const queueId of queueIds) {
const queue = context.getQueue(queueId);
await queue.addBulk(queues[queueId]);
await queue.disconnect();
}
}
}
};
};
32 changes: 17 additions & 15 deletions src/middleware/request-body.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import { RouteMiddleware } from '../types';
import { RequestError } from '../errors/request-error';

export const requestBody = (schemaName?: string): RouteMiddleware => async (context, next) => {
if (context.request.body) {
if (schemaName === 'create-sub-task') {
const items = Array.isArray(context.request.body) ? context.request.body : [context.request.body];
for (const body of items) {
const valid = context.ajv.validate('create-task', body);
export const requestBody =
(schemaName?: string): RouteMiddleware =>
async (context, next) => {
if (context.request.body) {
if (schemaName === 'create-sub-task') {
const items = Array.isArray(context.request.body) ? context.request.body : [context.request.body];
for (const body of items) {
const valid = context.ajv.validate('create-task', body);
if (!valid) {
throw new RequestError(context.ajv.errorsText());
}
}
} else if (schemaName) {
const valid = context.ajv.validate(schemaName, context.request.body);
if (!valid) {
throw new RequestError(context.ajv.errorsText());
}
}
} else if (schemaName) {
const valid = context.ajv.validate(schemaName, context.request.body);
if (!valid) {
throw new RequestError(context.ajv.errorsText());
}
context.requestBody = context.request.body;
}
context.requestBody = context.request.body;
}
await next();
};
await next();
};
2 changes: 1 addition & 1 deletion src/routes/accept-task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { sql } from 'slonik';
import { getTask } from '../database/get-task';
import { mapSingleTask } from '../utility/map-single-task';

export const acceptTask: RouteMiddleware<{ id: string }, { omitSubtasks: boolean }> = async context => {
export const acceptTask: RouteMiddleware<{ id: string }, { omitSubtasks: boolean }> = async (context) => {
const id = context.params.id;
const scope = context.state.jwt.scope;
const userId = context.state.jwt.user.id;
Expand Down
4 changes: 2 additions & 2 deletions src/routes/create-subtask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { getTask } from '../database/get-task';
import { validateEvents } from '../utility/events';
import { mapSingleTask } from '../utility/map-single-task';

export const createSubtask: RouteMiddleware<{ id: string }, CreateTask | CreateTask[]> = async context => {
export const createSubtask: RouteMiddleware<{ id: string }, CreateTask | CreateTask[]> = async (context) => {
const parentId = context.params.id;
const isAdmin = context.state.jwt.scope.indexOf('tasks.admin') !== -1;
const canCreate = isAdmin || context.state.jwt.scope.indexOf('tasks.create') !== -1;
Expand All @@ -28,7 +28,7 @@ export const createSubtask: RouteMiddleware<{ id: string }, CreateTask | CreateT
const returnTasks: any[] = [];
const isMany = Array.isArray(context.requestBody);
const tasks: CreateTask[] = isMany ? (context.requestBody as CreateTask[]) : [context.requestBody as CreateTask];
await context.connection.transaction(async connection => {
await context.connection.transaction(async (connection) => {
const rootTaskId = parentTask.root_task
? parentTask.root_task
: parentTask.parent_task
Expand Down
2 changes: 1 addition & 1 deletion src/routes/delete-subtasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { NotFound } from '../errors/not-found';
import { sql } from 'slonik';
import { castStringBool } from '../utility/cast-string-bool';

export const deleteSubtasks: RouteMiddleware<{ id: string }> = async context => {
export const deleteSubtasks: RouteMiddleware<{ id: string }> = async (context) => {
if (context.state.jwt.scope.indexOf('tasks.admin') === -1) {
throw new NotFound();
}
Expand Down
2 changes: 1 addition & 1 deletion src/routes/delete-task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { RouteMiddleware } from '../types';
import { NotFound } from '../errors/not-found';
import { sql } from 'slonik';

export const deleteTask: RouteMiddleware<{ id: string }> = async context => {
export const deleteTask: RouteMiddleware<{ id: string }> = async (context) => {
if (context.state.jwt.scope.indexOf('tasks.admin') === -1) {
throw new NotFound();
}
Expand Down
4 changes: 2 additions & 2 deletions src/routes/delete-tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ export const batchDeleteTasks: RouteMiddleware = async (context, next) => {
throw new RequestError();
}

if (!!resourceId) {
if (resourceId) {
await context.connection.query(sql`
delete from tasks
where state ->> 'resourceId' = ${String(resourceId)};
`);
}

if (!!subject) {
if (subject) {
await context.connection.query(sql`
delete from tasks
where subject = ${subject}
Expand Down
7 changes: 3 additions & 4 deletions src/routes/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@ import { RouteMiddleware } from '../types';
import { sql } from 'slonik';
import { NotFound } from '../errors/not-found';

export const postEvent: RouteMiddleware<
{ id: string; event: string },
{ subject?: string; state?: any }
> = async context => {
export const postEvent: RouteMiddleware<{ id: string; event: string }, { subject?: string; state?: any }> = async (
context
) => {
const id = context.params.id;
const event = context.params.event;
const isAdmin = context.state.jwt.scope.indexOf('tasks.admin') !== -1;
Expand Down
2 changes: 1 addition & 1 deletion src/routes/export-tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { sql } from 'slonik';
import { NotFound } from '../errors/not-found';
import { RouteMiddleware } from '../types';

export const exportTasks: RouteMiddleware = async context => {
export const exportTasks: RouteMiddleware = async (context) => {
const isAdmin = context.state.jwt.scope.indexOf('tasks.admin') !== -1;

if (!isAdmin) {
Expand Down
4 changes: 2 additions & 2 deletions src/routes/get-all-tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ function getStatus(statusQuery: string) {
return sql`and t.status = any (${sql.array(parsedStatuses, sql`int[]`)})`;
}

export const getAllTasks: RouteMiddleware = async context => {
export const getAllTasks: RouteMiddleware = async (context) => {
// Subject facet.
// Type filter.
// Include sub-tasks filter.
Expand Down Expand Up @@ -155,7 +155,7 @@ export const getAllTasks: RouteMiddleware = async context => {
);

context.response.body = {
tasks: taskList.map(task => mapSingleTask(task)),
tasks: taskList.map((task) => mapSingleTask(task)),
pagination: {
page,
totalResults: rowCount,
Expand Down
8 changes: 6 additions & 2 deletions src/routes/get-single-task.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { RouteMiddleware } from '../types';
import { getTask } from '../database/get-task';

export const getSingleTask: RouteMiddleware<{ id: string }> = async context => {
export const getSingleTask: RouteMiddleware<{ id: string }> = async (context) => {
const assignee = Boolean(context.query.assignee);
context.response.body = await getTask(context.connection, {
context: context.state.jwt.context,
Expand All @@ -12,6 +12,10 @@ export const getSingleTask: RouteMiddleware<{ id: string }> = async context => {
page: Number(context.query.page || 1),
all: Boolean(context.query.all),
subtaskFields: assignee ? ['assignee'] : [],
subjects: Array.isArray(context.query.subjects) ? context.query.subjects : context.query.subjects ? [context.query.subjects] : [],
subjects: Array.isArray(context.query.subjects)
? context.query.subjects
: context.query.subjects
? [context.query.subjects]
: [],
});
};
Loading

0 comments on commit 3bcce27

Please sign in to comment.