Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
read(){
let {middlewares, options} = parse_args(arguments, {
joins: [],
sortable: [],
searchable: [],
filterable: [],
pagination:undefined,
fetch: {},
fetchItem: {},
});
let {collection, options:{id}, pattern} = this;
this.methods.read = true;
// read list
this.get(pattern.root,
convert(paginate(options.pagination)),
compose(middlewares),
async (ctx) => {
let query = ctx.state.query || collection(ctx).model.forge();
if (collection(ctx).relatedData) {
query = query.where({[collection(ctx).relatedData.key('foreignKey')]:collection(ctx).relatedData.parentId})
}
if (options.joins) {
options.joins.forEach(relation => query.join(relation));
}
if (options.sortable) {
let order_by = _.get(ctx, 'request.query.sort', _.first(options.sortable));
if (_.includes(options.sortable, _.trimStart(order_by, '-'))) {
query = query.orderBy(order_by, order_by[0] == '-' ? 'DESC' : 'ASC');
}
}
if (options.filterable) {
let filters = options.filterable.map(filter => {
export default function middleware() {
return compose([
logger(),
helmet(), // reset HTTP headers (e.g. remove x-powered-by)
convert(cors()),
convert(bodyParser()),
convert(session()),
]);
}
... tenant ? {[TENANT_HEADER]: formatTenantHeaderValue(tenant)} : null,
... binding ? {[BINDING_HEADER]: formatBindingHeaderValue(binding)} : null,
... locale ? {[LOCALE_HEADER]: locale} : null,
... operationId ? {'x-vtex-operation-id': operationId} : null,
... product ? {[PRODUCT_HEADER]: product} : null,
... segmentToken ? {[SEGMENT_HEADER]: segmentToken} : null,
... sessionToken ? {[SESSION_HEADER]: sessionToken} : null,
}
if (authType && authToken) {
headers['Authorization'] = `${authType} ${authToken}` // tslint:disable-line
}
const memoizedCache = new Map>()
this.runMiddlewares = compose([...opts.middlewares || [],
defaultsMiddleware(baseURL, headers, params, timeout, retries, verbose),
metricsMiddleware({metrics, serverTiming, name}),
memoizationMiddleware({memoizedCache}),
...recorder ? [recorderMiddleware(recorder)] : [],
cancellationToken(cancellation),
singleFlightMiddleware,
acceptNotFoundMiddleware,
...memoryCache ? [cacheMiddleware({type: CacheType.Memory, storage: memoryCache})] : [],
...diskCache ? [cacheMiddleware({type: CacheType.Disk, storage: diskCache})] : [],
notFoundFallbackMiddleware,
routerCacheMiddleware,
requestMiddleware(limit),
])
}
// error: {},
// tslint:disable-next-line no-var-before-return
return result;
} catch (error) {
return {
type: 'error',
message: error.message,
};
}
};
return {
name: 'rpc',
path: '/rpc',
middleware: compose([
koaCompress(),
bodyParser(),
async (ctx: Context): Promise => {
if (!ctx.is('application/json')) {
return ctx.throw(415);
}
// tslint:disable-next-line no-any
const { body } = ctx.request as any;
const logger = getLogger(ctx);
const result = await handleRequestSafe(logger, body);
ctx.status = 200;
ctx.body = result;
},
]),
) => (paths: PathItem): Application => {
const app = new Koa();
const serverMiddlewares = koaCompose([
...createRouteMiddlewares(paths),
setRequestStateMiddleware,
cacheMiddleware,
createProcessingMiddleware(middlewares)
]);
app.use(serverMiddlewares);
app.listen(port);
console.log(`Mock server working on :${port}`);
return app;
};
export function token() {
return compose([
passport.authenticate(['basic', 'clientPassword'], { session: false }),
server.token(),
server.errorHandler()
]);
}
const {status, body} = $body;
cx.status = status;
cx.body = body;
}
}
const middlewares = [
catchError,
compress(),
bodyparser(),
loadConfig(withStatic),
loadConfig(withFavicon),
loadRoutes
];
export default compose(middlewares);
post(name, context, next) {
const middlewares = this.middlewares[name];
if (middlewares) {
return compose(middlewares)(context || {}, next);
}
return Promise.resolve();
}
monitored('app-tokens.update'),
async (ctx) => {
const { state: { user }, request: { body: { title } } } = ctx;
const token = await dbAdapter.getAppTokenById(ctx.params.tokenId);
if (!token || token.userId !== user.id || !token.isActive) {
throw new NotFoundException('Token not found');
}
await token.setTitle(title);
ctx.body = { token: serializeAppToken(token) };
},
]);
export const list = compose([
authRequired(),
monitored('app-tokens.update'),
async (ctx) => {
const { state: { user } } = ctx;
const tokens = await dbAdapter.listActiveAppTokens(user.id);
ctx.body = { tokens: tokens.map(serializeAppToken) };
},
]);
export const scopes = (ctx) => (ctx.body = { scopes: appTokensScopes });
function serializeAppToken(token) {
return pick(token, [
'id',
export default function routes() {
return compose(
[
router.routes(),
router.allowedMethods()
]
)
}