Fix flow errors

This commit is contained in:
Jori Lallo
2017-05-09 23:14:24 -07:00
parent e051713177
commit 75ad27658e
19 changed files with 519 additions and 179 deletions

View File

@@ -1,10 +1,7 @@
import httpErrors from 'http-errors';
import JWT from 'jsonwebtoken';
import {
User,
ApiKey,
} from '../../models';
import { User, ApiKey } from '../../models';
export default function auth({ require = true } = {}) {
return async function authMiddleware(ctx, next) {
@@ -22,8 +19,10 @@ export default function auth({ require = true } = {}) {
}
} else {
if (require) {
throw httpErrors.Unauthorized(`Bad Authorization header format. \
Format is "Authorization: Bearer <token>"\n`);
throw httpErrors.Unauthorized(
`Bad Authorization header format. \
Format is "Authorization: Bearer <token>"\n`
);
}
}
} else if (ctx.body.token) {
@@ -43,9 +42,11 @@ export default function auth({ require = true } = {}) {
// API key
let apiKey;
try {
apiKey = await ApiKey.findOne({ where: {
secret: token,
} });
apiKey = await ApiKey.findOne({
where: {
secret: token,
},
});
} catch (e) {
throw httpErrors.Unauthorized('Invalid api key');
}

View File

@@ -18,7 +18,9 @@ export default function pagination(options) {
offset = isNaN(offset) ? 0 : offset;
if (limit > opts.maxLimit) {
throw httpErrors.BadRequest(`Pagination limit is too large (max ${opts.maxLimit})`);
throw httpErrors.BadRequest(
`Pagination limit is too large (max ${opts.maxLimit})`
);
}
ctx.state.pagination = {
@@ -28,8 +30,9 @@ export default function pagination(options) {
query.limit = ctx.state.pagination.limit;
query.offset = ctx.state.pagination.offset + query.limit;
ctx.state.pagination.nextPath = '/api' + ctx.request.path + '?' + querystring.stringify(query);
ctx.state.pagination.nextPath =
'/api' + ctx.request.path + '?' + querystring.stringify(query);
return next();
}
};
};
}

View File

@@ -5,6 +5,4 @@ const apiError = (code, id, message) => {
};
export default apiError;
export {
httpErrors,
};
export { httpErrors };

View File

@@ -22,37 +22,45 @@ if (process.env.NODE_ENV === 'development') {
const compile = webpack(config);
/* eslint-enable global-require */
app.use(convert(devMiddleware(compile, {
// display no info to console (only warnings and errors)
noInfo: true,
app.use(
convert(
devMiddleware(compile, {
// display no info to console (only warnings and errors)
noInfo: true,
// display nothing to the console
quiet: false,
// display nothing to the console
quiet: false,
// switch into lazy mode
// that means no watching, but recompilation on every request
lazy: false,
// switch into lazy mode
// that means no watching, but recompilation on every request
lazy: false,
// // watch options (only lazy: false)
// watchOptions: {
// aggregateTimeout: 300,
// poll: true
// },
// // watch options (only lazy: false)
// watchOptions: {
// aggregateTimeout: 300,
// poll: true
// },
// public path to bind the middleware to
// use the same as in webpack
publicPath: config.output.publicPath,
// public path to bind the middleware to
// use the same as in webpack
publicPath: config.output.publicPath,
// options for formating the statistics
stats: {
colors: true,
},
})));
app.use(convert(hotMiddleware(compile, {
log: console.log, // eslint-disable-line
path: '/__webpack_hmr',
heartbeat: 10 * 1000,
})));
// options for formating the statistics
stats: {
colors: true,
},
})
)
);
app.use(
convert(
hotMiddleware(compile, {
log: console.log, // eslint-disable-line
path: '/__webpack_hmr',
heartbeat: 10 * 1000,
})
)
);
app.use(logger());
}
@@ -63,11 +71,13 @@ if (process.env.NODE_ENV === 'production') {
app.use(mount('/api', api));
app.use(mount(routes));
app.use(helmet.csp({
directives: {
defaultSrc: ['\'self\''],
styleSrc: ['\'self\'', '\'unsafe-inline\''],
},
}));
app.use(
helmet.csp({
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
},
})
);
export default app;

View File

@@ -3,9 +3,7 @@ import { Document, Atlas, User } from './models';
import presentUser from './presenters/user';
export {
presentUser,
};
export { presentUser };
export function presentTeam(ctx, team) {
ctx.cache.set(team.id, team);
@@ -43,15 +41,14 @@ export async function presentDocument(ctx, document, options) {
};
if (options.includeCollection) {
data.collection = await ctx.cache.get(
document.atlasId,
async () => {
const collection = await Atlas.findOne({ where: {
data.collection = await ctx.cache.get(document.atlasId, async () => {
const collection = await Atlas.findOne({
where: {
id: document.atlasId,
} });
return await presentCollection(ctx, collection);
}
);
},
});
return await presentCollection(ctx, collection);
});
}
if (options.includeCollaborators) {
@@ -62,8 +59,7 @@ export async function presentDocument(ctx, document, options) {
$in: document.collaboratorIds || [],
},
},
})
.map(user => presentUser(ctx, user));
}).map(user => presentUser(ctx, user));
}
const createdBy = await ctx.cache.get(
@@ -81,7 +77,11 @@ export async function presentDocument(ctx, document, options) {
return data;
}
export function presentCollection(ctx, collection, includeRecentDocuments=false) {
export function presentCollection(
ctx,
collection,
includeRecentDocuments = false
) {
ctx.cache.set(collection.id, collection);
return new Promise(async (resolve, _reject) => {
@@ -95,7 +95,8 @@ export function presentCollection(ctx, collection, includeRecentDocuments=false)
updatedAt: collection.updatedAt,
};
if (collection.type === 'atlas') data.navigationTree = collection.navigationTree;
if (collection.type === 'atlas')
data.navigationTree = collection.navigationTree;
if (includeRecentDocuments) {
const documents = await Document.findAll({
@@ -103,18 +104,24 @@ export function presentCollection(ctx, collection, includeRecentDocuments=false)
atlasId: collection.id,
},
limit: 10,
order: [
['updatedAt', 'DESC'],
],
order: [['updatedAt', 'DESC']],
});
const recentDocuments = [];
await Promise.all(documents.map(async (document) => {
recentDocuments.push(await presentDocument(ctx, document, {
includeCollaborators: true,
}));
}));
data.recentDocuments = _.orderBy(recentDocuments, ['updatedAt'], ['desc']);
await Promise.all(
documents.map(async document => {
recentDocuments.push(
await presentDocument(ctx, document, {
includeCollaborators: true,
})
);
})
);
data.recentDocuments = _.orderBy(
recentDocuments,
['updatedAt'],
['desc']
);
}
resolve(data);

View File

@@ -4,7 +4,4 @@ import redisLock from 'redis-lock';
const client = redis.createClient(process.env.REDIS_URL);
const lock = redisLock(client);
export {
client,
lock,
};
export { client, lock };

View File

@@ -9,9 +9,10 @@ import subdomainRedirect from './middlewares/subdomainRedirect';
const koa = new Koa();
const router = new Router();
router.get('/service-worker.js', async (ctx) => {
router.get('/service-worker.js', async ctx => {
ctx.set('Content-Type', 'application/javascript');
if (process.env.NODE_ENV === 'production') ctx.set('Cache-Control', `max-age=${30}`);
if (process.env.NODE_ENV === 'production')
ctx.set('Cache-Control', `max-age=${30}`);
await sendfile(ctx, path.join(__dirname, './static/service-worker.js'));
if (!ctx.status) ctx.throw(httpErrors.NotFound());
});
@@ -19,22 +20,25 @@ router.get('/service-worker.js', async (ctx) => {
router.get('/_health', ctx => (ctx.body = 'OK'));
if (process.env.NODE_ENV === 'production') {
router.get('/static/*', async (ctx) => {
router.get('/static/*', async ctx => {
ctx.set({
'Cache-Control': `max-age=${356 * 24 * 60 * 60}`,
});
await sendfile(ctx, path.join(__dirname, '../dist/', ctx.path.substring(8)));
await sendfile(
ctx,
path.join(__dirname, '../dist/', ctx.path.substring(8))
);
});
router.get('*', async (ctx) => {
router.get('*', async ctx => {
await sendfile(ctx, path.join(__dirname, '../dist/index.html'));
if (!ctx.status) ctx.throw(httpErrors.NotFound());
});
koa.use(subdomainRedirect());
} else {
router.get('*', async (ctx) => {
router.get('*', async ctx => {
await sendfile(ctx, path.join(__dirname, './static/dev.html'));
if (!ctx.status) ctx.throw(httpErrors.NotFound());
});