Run prettier

This commit is contained in:
rijkvanzanten
2020-09-22 16:11:28 -04:00
parent e703d1e928
commit 85ca7b5d17
25 changed files with 203 additions and 129 deletions

View File

@@ -55,13 +55,13 @@ app.set('trust proxy', true);
app.use(expressLogger({ logger }));
app.use((req, res, next) => {
bodyParser.json()(req, res, err => {
if (err) {
bodyParser.json()(req, res, (err) => {
if (err) {
return next(new InvalidPayloadException(err.message));
}
}
return next();
});
return next();
});
});
app.use(bodyParser.json());
@@ -129,7 +129,6 @@ registerExtensions(customRouter);
track('serverStarted');
emitter.emitAsync('server.started')
.catch((err) => logger.warn(err));
emitter.emitAsync('server.started').catch((err) => logger.warn(err));
export default app;

View File

@@ -27,18 +27,19 @@ function getKevyInstance() {
}
}
function getConfig(
store: 'memory' | 'redis' | 'memcache' = 'memory'
): Options<any> {
const config: Options<any> = { namespace: env.CACHE_NAMESPACE, ttl: ms(env.CACHE_TTL as string) };
function getConfig(store: 'memory' | 'redis' | 'memcache' = 'memory'): Options<any> {
const config: Options<any> = {
namespace: env.CACHE_NAMESPACE,
ttl: ms(env.CACHE_TTL as string),
};
if (store === 'redis') {
const Redis = require('ioredis');
const KeyvRedis = require('@keyv/redis');
config.store = new KeyvRedis(new Redis(
env.CACHE_REDIS || getConfigFromEnv('CACHE_REDIS_')
));
config.store = new KeyvRedis(
new Redis(env.CACHE_REDIS || getConfigFromEnv('CACHE_REDIS_'))
);
}
if (store === 'memcache') {

View File

@@ -5,7 +5,7 @@ export default async function migrate(direction: 'latest' | 'up' | 'down') {
try {
await run(database, direction);
} catch(err) {
} catch (err) {
console.log(err);
process.exit(1);
} finally {

View File

@@ -19,9 +19,18 @@ program.command('init').description('Create a new Directus Project').action(init
const dbCommand = program.command('database');
dbCommand.command('install').description('Install the database').action(dbInstall);
dbCommand.command('migrate:latest').description('Upgrade the database').action(() => dbMigrate('latest'));
dbCommand.command('migrate:up').description('Upgrade the database').action(() => dbMigrate('up'));
dbCommand.command('migrate:down').description('Downgrade the database').action(() => dbMigrate('down'));
dbCommand
.command('migrate:latest')
.description('Upgrade the database')
.action(() => dbMigrate('latest'));
dbCommand
.command('migrate:up')
.description('Upgrade the database')
.action(() => dbMigrate('up'));
dbCommand
.command('migrate:down')
.description('Downgrade the database')
.action(() => dbMigrate('down'));
const usersCommand = program.command('users');
usersCommand
@@ -34,7 +43,7 @@ usersCommand
const rolesCommand = program.command('roles');
rolesCommand
.command('create')
.command('create')
.storeOptionsAsProperties(false)
.passCommandToAction(false)
.description('Create a new role')

View File

@@ -24,7 +24,7 @@ router.get(
};
return next();
}),
})
);
router.get(
@@ -38,7 +38,7 @@ router.get(
};
return next();
}),
})
);
router.post(
@@ -69,7 +69,7 @@ router.post(
}
return next();
}),
})
);
router.patch(
@@ -93,7 +93,7 @@ router.patch(
}
return next();
}),
})
);
router.delete(
@@ -103,7 +103,7 @@ router.delete(
await service.delete(req.params.pk);
return next();
}),
})
);
export default router;

View File

@@ -112,7 +112,9 @@ router.post(
try {
const record = await service.readByKey(keys as any, req.sanitizedQuery);
res.locals.payload = { data: res.locals.savedFiles.length === 1 ? record[0] : record || null };
res.locals.payload = {
data: res.locals.savedFiles.length === 1 ? record[0] : record || null,
};
} catch (error) {
if (error instanceof ForbiddenException) {
return next();
@@ -127,7 +129,7 @@ router.post(
const importSchema = Joi.object({
url: Joi.string().required(),
data: Joi.object()
data: Joi.object(),
});
router.post(

View File

@@ -1,6 +1,6 @@
import express from 'express';
import asyncHandler from 'express-async-handler';
import {FoldersService, MetaService} from '../services';
import { FoldersService, MetaService } from '../services';
import { ForbiddenException } from '../exceptions';
import useCollection from '../middleware/use-collection';

View File

@@ -1,7 +1,7 @@
import express from 'express';
import asyncHandler from 'express-async-handler';
import collectionExists from '../middleware/collection-exists';
import { ItemsService, MetaService} from '../services';
import { ItemsService, MetaService } from '../services';
import { RouteNotFoundException, ForbiddenException } from '../exceptions';
const router = express.Router();
@@ -29,7 +29,7 @@ router.post(
}
return next();
}),
})
);
router.get(
@@ -50,7 +50,7 @@ router.get(
data: records || null,
};
return next();
}),
})
);
router.get(
@@ -69,7 +69,7 @@ router.get(
data: result || null,
};
return next();
}),
})
);
router.patch(
@@ -100,7 +100,7 @@ router.patch(
}
return next();
}),
})
);
router.patch(
@@ -128,7 +128,7 @@ router.patch(
}
return next();
}),
})
);
router.delete(
@@ -139,7 +139,7 @@ router.delete(
const pk = req.params.pk.includes(',') ? req.params.pk.split(',') : req.params.pk;
await service.delete(pk as any);
return next();
}),
})
);
export default router;

View File

@@ -1,6 +1,6 @@
import express from 'express';
import asyncHandler from 'express-async-handler';
import { RevisionsService, MetaService} from '../services';
import { RevisionsService, MetaService } from '../services';
import useCollection from '../middleware/use-collection';
const router = express.Router();

View File

@@ -1,6 +1,6 @@
import express from 'express';
import asyncHandler from 'express-async-handler';
import { RolesService, MetaService} from '../services';
import { RolesService, MetaService } from '../services';
import { ForbiddenException } from '../exceptions';
import useCollection from '../middleware/use-collection';

View File

@@ -1,7 +1,11 @@
import express from 'express';
import asyncHandler from 'express-async-handler';
import Joi from 'joi';
import { InvalidPayloadException, InvalidCredentialsException, ForbiddenException } from '../exceptions';
import {
InvalidPayloadException,
InvalidCredentialsException,
ForbiddenException,
} from '../exceptions';
import { UsersService, MetaService, AuthenticationService } from '../services';
import useCollection from '../middleware/use-collection';

View File

@@ -1,6 +1,6 @@
import express from 'express';
import asyncHandler from 'express-async-handler';
import { WebhooksService, MetaService} from '../services';
import { WebhooksService, MetaService } from '../services';
import { ForbiddenException } from '../exceptions';
import useCollection from '../middleware/use-collection';

View File

@@ -7,13 +7,16 @@ type Migration = {
version: string;
name: string;
timestamp: Date;
}
};
export default async function run(database: Knex, direction: 'up' | 'down' | 'latest') {
let migrationFiles = await fse.readdir(__dirname);
migrationFiles = migrationFiles.filter((file: string) => file !== 'run.ts');
const completedMigrations = await database.select<Migration[]>('*').from('directus_migrations').orderBy('version');
const completedMigrations = await database
.select<Migration[]>('*')
.from('directus_migrations')
.orderBy('version');
const migrations = migrationFiles.map((migrationFile) => {
const version = migrationFile.split('-')[0];
@@ -24,7 +27,7 @@ export default async function run(database: Knex, direction: 'up' | 'down' | 'la
file: migrationFile,
version,
name,
completed
completed,
};
});
@@ -51,7 +54,9 @@ export default async function run(database: Knex, direction: 'up' | 'down' | 'la
const { up } = require(path.join(__dirname, nextVersion.file));
await up(database);
await database.insert({ version: nextVersion.version, name: nextVersion.name }).into('directus_migrations');
await database
.insert({ version: nextVersion.version, name: nextVersion.name })
.into('directus_migrations');
}
async function down() {
@@ -61,7 +66,9 @@ export default async function run(database: Knex, direction: 'up' | 'down' | 'la
throw Error('Nothing to downgrade');
}
const migration = migrations.find((migration) => migration.version === currentVersion.version);
const migration = migrations.find(
(migration) => migration.version === currentVersion.version
);
if (!migration) {
throw new Error('Couldnt find migration');
@@ -77,7 +84,9 @@ export default async function run(database: Knex, direction: 'up' | 'down' | 'la
if (migration.completed === false) {
const { up } = require(path.join(__dirname, migration.file));
await up(database);
await database.insert({ version: migration.version, name: migration.name }).into('directus_migrations');
await database
.insert({ version: migration.version, name: migration.name })
.into('directus_migrations');
}
}
}

View File

@@ -8,9 +8,9 @@ import applyQuery from '../utils/apply-query';
import Knex from 'knex';
type RunASTOptions = {
query?: AST['query'],
knex?: Knex
}
query?: AST['query'];
knex?: Knex;
};
export default async function runAST(ast: AST, options?: RunASTOptions) {
const query = options?.query || ast.query;

View File

@@ -22,14 +22,14 @@ type TableSeed = {
column: string;
};
};
}
}
};
};
type RowSeed = {
table: string;
defaults: Record<string, any>;
data: Record<string, any>[];
}
};
type FieldSeed = {
table: string;
@@ -50,7 +50,7 @@ type FieldSeed = {
translation: Record<string, any> | null;
note: string | null;
}[];
}
};
export default async function runSeed(database: Knex) {
const exists = await database.schema.hasTable('directus_collections');
@@ -68,10 +68,13 @@ async function createTables(database: Knex) {
const tableSeeds = await fse.readdir(path.resolve(__dirname, './01-tables/'));
for (const tableSeedFile of tableSeeds) {
const yamlRaw = await fse.readFile(path.resolve(__dirname, './01-tables', tableSeedFile), 'utf8');
const yamlRaw = await fse.readFile(
path.resolve(__dirname, './01-tables', tableSeedFile),
'utf8'
);
const seedData = yaml.safeLoad(yamlRaw) as TableSeed;
await database.schema.createTable(seedData.table, tableBuilder => {
await database.schema.createTable(seedData.table, (tableBuilder) => {
for (const [columnName, columnInfo] of Object.entries(seedData.columns)) {
let column: ColumnBuilder;
@@ -129,7 +132,10 @@ async function insertRows(database: Knex) {
const rowSeeds = await fse.readdir(path.resolve(__dirname, './02-rows/'));
for (const rowSeedFile of rowSeeds) {
const yamlRaw = await fse.readFile(path.resolve(__dirname, './02-rows', rowSeedFile), 'utf8');
const yamlRaw = await fse.readFile(
path.resolve(__dirname, './02-rows', rowSeedFile),
'utf8'
);
const seedData = yaml.safeLoad(yamlRaw) as RowSeed;
const dataWithDefaults = seedData.data.map((row) => {
@@ -149,11 +155,17 @@ async function insertRows(database: Knex) {
async function insertFields(database: Knex) {
const fieldSeeds = await fse.readdir(path.resolve(__dirname, './03-fields/'));
const defaultsYaml = await fse.readFile(path.resolve(__dirname, './03-fields/_defaults.yaml'), 'utf8');
const defaultsYaml = await fse.readFile(
path.resolve(__dirname, './03-fields/_defaults.yaml'),
'utf8'
);
const defaults = yaml.safeLoad(defaultsYaml) as FieldSeed;
for (const fieldSeedFile of fieldSeeds) {
const yamlRaw = await fse.readFile(path.resolve(__dirname, './03-fields', fieldSeedFile), 'utf8');
const yamlRaw = await fse.readFile(
path.resolve(__dirname, './03-fields', fieldSeedFile),
'utf8'
);
const seedData = yaml.safeLoad(yamlRaw) as FieldSeed;
if (fieldSeedFile === '_defaults.yaml') {

View File

@@ -3,6 +3,6 @@ import { EventEmitter2 } from 'eventemitter2';
const emitter = new EventEmitter2({ wildcard: true, verboseMemoryLeak: true, delimiter: '.' });
// No-op function to ensure we never end up with no data
emitter.on('item.*.*.before', input => input);
emitter.on('item.*.*.before', (input) => input);
export default emitter;

View File

@@ -19,9 +19,12 @@ export async function listExtensions(type: string) {
return await listFolders(location);
} catch (err) {
if (err.code === 'ENOENT') {
throw new ServiceUnavailableException(`Extension folder "extensions/${type}" couldn't be opened`, {
service: 'extensions',
});
throw new ServiceUnavailableException(
`Extension folder "extensions/${type}" couldn't be opened`,
{
service: 'extensions',
}
);
}
throw err;
}

View File

@@ -1,13 +1,18 @@
import { RequestHandler } from "express";
import asyncHandler from "express-async-handler";
import env from "../env";
import { getCacheKey } from "../utils/get-cache-key";
import { RequestHandler } from 'express';
import asyncHandler from 'express-async-handler';
import env from '../env';
import { getCacheKey } from '../utils/get-cache-key';
import cache from '../cache';
import { Transform, transforms } from 'json2csv';
import { PassThrough } from 'stream';
export const respond: RequestHandler = asyncHandler(async (req, res) => {
if (req.method.toLowerCase() === 'get' && env.CACHE_ENABLED === true && cache && !req.sanitizedQuery.export) {
if (
req.method.toLowerCase() === 'get' &&
env.CACHE_ENABLED === true &&
cache &&
!req.sanitizedQuery.export
) {
const key = getCacheKey(req);
await cache.set(key, res.locals.payload);
}
@@ -34,7 +39,9 @@ export const respond: RequestHandler = asyncHandler(async (req, res) => {
res.set('Content-Type', 'text/csv');
const stream = new PassThrough();
stream.end(Buffer.from(JSON.stringify(res.locals.payload.data), 'utf-8'));
const json2csv = new Transform({ transforms: [transforms.flatten({ separator: '.' })] });
const json2csv = new Transform({
transforms: [transforms.flatten({ separator: '.' })],
});
return stream.pipe(json2csv).pipe(res);
}
}

View File

@@ -56,7 +56,11 @@ const sanitizeQuery: RequestHandler = (req, res, next) => {
query.search = req.query.search;
}
if (req.query.export && typeof req.query.export === 'string' && ['json', 'csv'].includes(req.query.export)) {
if (
req.query.export &&
typeof req.query.export === 'string' &&
['json', 'csv'].includes(req.query.export)
) {
query.export = req.query.export as 'json' | 'csv';
}

View File

@@ -53,14 +53,18 @@ export class ItemsService implements AbstractService {
});
if (this.collection.startsWith('directus_') === false) {
const customProcessed = await emitter.emitAsync(`item.create.${this.collection}.before`, payloads, {
event: `item.create.${this.collection}.before`,
accountability: this.accountability,
collection: this.collection,
item: null,
action: 'create',
payload: payloads,
});
const customProcessed = await emitter.emitAsync(
`item.create.${this.collection}.before`,
payloads,
{
event: `item.create.${this.collection}.before`,
accountability: this.accountability,
collection: this.collection,
item: null,
action: 'create',
payload: payloads,
}
);
payloads = customProcessed[customProcessed.length - 1];
}
@@ -166,14 +170,16 @@ export class ItemsService implements AbstractService {
}
if (this.collection.startsWith('directus_') === false) {
emitter.emitAsync(`item.create.${this.collection}`, {
event: `item.create.${this.collection}`,
accountability: this.accountability,
collection: this.collection,
item: primaryKeys,
action: 'create',
payload: payloads,
}).catch(err => logger.warn(err));
emitter
.emitAsync(`item.create.${this.collection}`, {
event: `item.create.${this.collection}`,
accountability: this.accountability,
collection: this.collection,
item: primaryKeys,
action: 'create',
payload: payloads,
})
.catch((err) => logger.warn(err));
}
return primaryKeys;
@@ -186,7 +192,10 @@ export class ItemsService implements AbstractService {
const authorizationService = new AuthorizationService({
accountability: this.accountability,
});
let ast = await getASTFromQuery(this.collection, query, { accountability: this.accountability, knex: this.knex });
let ast = await getASTFromQuery(this.collection, query, {
accountability: this.accountability,
knex: this.knex,
});
if (this.accountability && this.accountability.admin !== true) {
ast = await authorizationService.processAST(ast);
@@ -219,15 +228,11 @@ export class ItemsService implements AbstractService {
},
};
let ast = await getASTFromQuery(
this.collection,
queryWithFilter,
{
accountability: this.accountability,
action,
knex: this.knex,
}
);
let ast = await getASTFromQuery(this.collection, queryWithFilter, {
accountability: this.accountability,
action,
knex: this.knex,
});
if (this.accountability && this.accountability.admin !== true) {
const authorizationService = new AuthorizationService({
@@ -259,14 +264,18 @@ export class ItemsService implements AbstractService {
let payload = clone(data);
if (this.collection.startsWith('directus_') === false) {
const customProcessed = await emitter.emitAsync(`item.update.${this.collection}.before`, payload, {
event: `item.update.${this.collection}.before`,
accountability: this.accountability,
collection: this.collection,
item: null,
action: 'update',
const customProcessed = await emitter.emitAsync(
`item.update.${this.collection}.before`,
payload,
});
{
event: `item.update.${this.collection}.before`,
accountability: this.accountability,
collection: this.collection,
item: null,
action: 'update',
payload,
}
);
payload = customProcessed[customProcessed.length - 1];
}
@@ -354,14 +363,16 @@ export class ItemsService implements AbstractService {
await cache.clear();
}
emitter.emitAsync(`item.update.${this.collection}`, {
event: `item.update.${this.collection}`,
accountability: this.accountability,
collection: this.collection,
item: key,
action: 'update',
payload,
}).catch(err => logger.warn(err));
emitter
.emitAsync(`item.update.${this.collection}`, {
event: `item.update.${this.collection}`,
accountability: this.accountability,
collection: this.collection,
item: key,
action: 'update',
payload,
})
.catch((err) => logger.warn(err));
return key;
}
@@ -438,14 +449,16 @@ export class ItemsService implements AbstractService {
await cache.clear();
}
emitter.emitAsync(`item.delete.${this.collection}`, {
event: `item.delete.${this.collection}`,
accountability: this.accountability,
collection: this.collection,
item: keys,
action: 'delete',
payload: null,
}).catch(err => logger.warn(err));
emitter
.emitAsync(`item.delete.${this.collection}`, {
event: `item.delete.${this.collection}`,
accountability: this.accountability,
collection: this.collection,
item: keys,
action: 'delete',
payload: null,
})
.catch((err) => logger.warn(err));
return key;
}

View File

@@ -175,7 +175,12 @@ export class PayloadService {
if (['create', 'update'].includes(action)) {
processedPayload.forEach((record) => {
for (const [key, value] of Object.entries(record)) {
if (Array.isArray(value) || (typeof value === 'object' && (value instanceof Date) !== true && value !== null)) {
if (
Array.isArray(value) ||
(typeof value === 'object' &&
value instanceof Date !== true &&
value !== null)
) {
record[key] = JSON.stringify(value);
}
}

View File

@@ -6,10 +6,10 @@ import Knex from 'knex';
import { Router } from 'express';
type ExtensionContext = {
services: typeof services,
exceptions: typeof exceptions,
database: Knex,
env: typeof env,
services: typeof services;
exceptions: typeof exceptions;
database: Knex;
env: typeof env;
};
export type HookRegisterFunction = (context: ExtensionContext) => Record<string, ListenerFn>;

View File

@@ -19,7 +19,7 @@ type GetASTOptions = {
accountability?: Accountability | null;
action?: PermissionsAction;
knex?: Knex;
}
};
export default async function getASTFromQuery(
collection: string,

View File

@@ -1,8 +1,10 @@
import { Request } from "express";
import { Request } from 'express';
import url from 'url';
export function getCacheKey(req: Request) {
const path = url.parse(req.originalUrl).pathname;
const key = `${req.accountability?.user || 'null'}-${path}-${JSON.stringify(req.sanitizedQuery)}`;
const key = `${req.accountability?.user || 'null'}-${path}-${JSON.stringify(
req.sanitizedQuery
)}`;
return key;
}

View File

@@ -48,7 +48,7 @@ async function getEnvInfo(event: string) {
store: env.CACHE_STORE,
},
storage: {
drivers: getStorageDrivers()
drivers: getStorageDrivers(),
},
cors: {
enabled: env.CORS_ENABLED,
@@ -57,15 +57,19 @@ async function getEnvInfo(event: string) {
transport: env.EMAIL_TRANSPORT,
},
oauth: {
providers: env.OAUTH_PROVIDERS.split(',').filter((p?: string) => p).map((p: string) => p.trim()),
providers: env.OAUTH_PROVIDERS.split(',')
.filter((p?: string) => p)
.map((p: string) => p.trim()),
},
db_client: env.DB_CLIENT
}
db_client: env.DB_CLIENT,
};
}
function getStorageDrivers() {
const drivers: string[] = [];
const locations = env.STORAGE_LOCATIONS.split(',').filter((l?: string) => l).map((l: string) => l.trim());
const locations = env.STORAGE_LOCATIONS.split(',')
.filter((l?: string) => l)
.map((l: string) => l.trim());
for (const location of locations) {
const driver = env[`STORAGE_${location.toUpperCase()}_DRIVER`];