Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 12x 7x 7x 7x 19x 15x 4x 1x 3x 22x 22x 2x 20x 20x 20x 12x 12x 7x 12x 9x 9x 9x 9x 9x 9x 9x 12x 9x 9x 9x 9x 5x 5x 4x 2x 4x 4x 2x 1x 1x 1x 4x 1x 4x 2x 7x 7x 4x 1x 1x 3x 7x 6x 6x 6x 4x 4x 4x 9x 9x 9x 9x 9x 5x 4x 4x 9x 5x 5x 5x 4x 4x 17x 1x 16x 16x 19x 19x 15x 15x 16x 16x | /*!
* The MIT License (MIT)
*
* Copyright (c) 2017 Vlad Martynenko <vladimir.martynenko.work@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Contains configuration options for the main function
*/
import {
FieldValidationObject,
onUnhandledError,
ValidityConfig
} from "./helpers";
import {
defaultProfilingResultHandler,
storeProfilingInfo
} from "./profiling";
import {
getValidationResults,
getValidators
} from "./validation";
import hapiMiddleware from './hapi-middleware';
import expressMiddleware from './express-middleware';
import koaMiddleware from './koa-middleware';
// Indicates whether schema entity was already processed
export const Processed = Symbol();
let profilingResultHandler: any = {
handler: defaultProfilingResultHandler
};
// Set of middleware functions for express, koa and hapi servers
export const graphQLValidityHapiMiddleware = hapiMiddleware(profilingResultHandler);
export const graphQLValidityExpressMiddleware = expressMiddleware(profilingResultHandler);
export const graphQLValidityKoaMiddleware = koaMiddleware(profilingResultHandler);
/**
* Top level wrapper for the GraphQL schema entities
* which replaces resolve function if any found
*
* @param entity - GraphQL object entity
* @param {ValidityConfig} config - setup options for the wrapper function
*/
export function wrapResolvers(entity: any, config?: ValidityConfig) {
if (!config) {
config = {
wrapErrors: false,
enableProfiling: false,
unhandledErrorWrapper: onUnhandledError
}
}
else {
config.unhandledErrorWrapper = config.unhandledErrorWrapper
|| onUnhandledError;
Eif (config.enableProfiling) {
profilingResultHandler.handler = config.profilingResultHandler ?
config.profilingResultHandler : profilingResultHandler.handler;
}
}
if (entity.constructor.name === 'GraphQLSchema') {
wrapSchema(entity, config);
} else if (entity.constructor.name === 'GraphQLObjectType') {
wrapType(entity, config);
} else {
wrapField(entity, config);
}
}
/**
* Internal function which performs resolvers wrapping with common async function
*
* @param field - GraphQL entity field
* @param {ValidityConfig} config - setup options for the wrapper function
*/
function wrapField(
field: any,
config: ValidityConfig
) {
const resolve = field.resolve;
if (field[Processed] || !resolve) {
return;
}
field[Processed] = true;
field.resolve = validateFieldResolution(field, config, resolve);
}
/**
* Creates new field resolver for a given graphql field node
*
* @param field - field node which gets resolver replaced
* @param {ValidityConfig} config - config options for validation
* @param {Function} resolver - original resolver function
*
* @returns {(...args: any[]) => (Promise<any> | any)} - new resolver function
*/
function validateFieldResolution(
field: any,
config: ValidityConfig,
resolver: Function
) {
return function (...args: any[]) {
const requestContext: FieldValidationObject = { fieldName: field.name };
if (config.enableProfiling) {
// profiling start time
requestContext.pst = Date.now();
}
for (let i = 0, s = args.length; i < s; i++) {
let arg = args[i];
Eif (arg && arg.rootValue && arg.rootValue.__graphQLValidity) {
arg.rootValue.__graphQLValidity.config = config;
requestContext.validity = arg.rootValue.__graphQLValidity;
}
Eif (arg && arg.parentType) {
requestContext.astPath = arg.path;
requestContext.parentTypeName = arg.parentType;
}
}
if (requestContext.validity) {
let validationResults = getValidationResults(requestContext.validity);
let validators = getValidators(
field,
String(requestContext.parentTypeName),
requestContext.validity
);
const result = processValidators(validators, validationResults, args);
if (result && result.then) {
return new Promise((
resolve: Function,
reject: Function
) => {
result.then(() => {
if (config.enableProfiling) {
// validation end time
requestContext.vet = Date.now();
}
const result = resolver.apply(this, args);
if (config.enableProfiling) {
if (result && result.then) {
result.then(() => {
processProfiling(requestContext);
})
}
else {
processProfiling(requestContext);
}
}
resolve(result);
}).catch(e => {
reject(e);
});
});
}
else {
if (config.enableProfiling) {
// validation end time
requestContext.vet = Date.now();
}
}
}
const result = resolver.apply(this, args);
if (config.enableProfiling) {
if (result && result.then) {
result.then(() => {
processProfiling(requestContext);
});
}
else {
processProfiling(requestContext);
}
}
return result;
};
}
/**
* Creates profiling data using process context for a field
*
* @param {FieldValidationObject} requestContext - data gathered during field validation and execution
*/
function processProfiling(requestContext: FieldValidationObject) {
// execution end time
requestContext.eet = Date.now();
try {
if (requestContext.validity) {
const validation = <number>requestContext.vet - <number>requestContext.pst;
const execution = <number>requestContext.eet - <number>requestContext.vet;
storeProfilingInfo(requestContext.validity, requestContext.astPath, {
name: requestContext.fieldName,
validation,
execution,
fieldsExecution: 0,
totalExecution: validation + execution
});
}
}
catch (err) {
console.error('Profiling failed!', err);
}
}
/**
* Validator function executor
*
* @param {Function[]} validators - array of validation functions
* @param {any[]} validationResults - static array of validation results
* @param {any[]} args - original resolver arguments
*
* @returns {Promise<void>} - return promise if at least one validator was returning promise
*/
function processValidators(
validators: Function[],
validationResults: any[],
args: any[]
) {
let promises = [];
for (let i = 0, s = validators.length; i < s; i++) {
let validator = validators[i];
let validationResult = validator.apply(this, args) || [];
if (validationResult.then) {
promises.push(validationResult);
}
else {
validationResult = Array.isArray(validationResult) ? validationResult : [validationResult];
Array.prototype.push.apply(
validationResults,
validationResult
);
}
}
if (promises.length) {
return handleValidationPromises(promises, validationResults);
}
}
/**
* Synchronises validator promises execution
*
* @param {any[]} promises - array of validator promises
* @param {any[]} validationResults - static array of validation results
*
* @returns {Promise<void>} - general promise for all validator promises
*/
async function handleValidationPromises(
promises: any[],
validationResults: any[]
) {
for (let promise of promises) {
let validationResult = (await promise) || [];
validationResult = Array.isArray(validationResult) ? validationResult : [validationResult];
Array.prototype.push.apply(
validationResults,
validationResult
);
}
}
/**
* Wraps each field of the GraphQLObjectType entity
*
* @param {GraphQLObjectType} type - GraphQLObject schema entity
* @param {ValidityConfig} config - setup options for the wrapper function
*/
function wrapType(type: any, config: ValidityConfig) {
if (type[Processed] || !type.getFields) {
return;
}
const fields = type.getFields();
for (const fieldName in fields) {
Iif (!Object.hasOwnProperty.call(fields, fieldName)) {
continue;
}
wrapField(fields[fieldName], config);
}
}
/**
* Wraps each GraphQLObjectType fields resolver for entire GraphQL Schema
*
* @param {GraphQLSchema} schema - schema object that must be wrapped
* @param {ValidityConfig} config - setup options for the wrapper function
*/
function wrapSchema(schema: any, config: ValidityConfig) {
const types = schema.getTypeMap();
for (const typeName in types) {
Iif (!Object.hasOwnProperty.call(types, typeName)) {
continue;
}
wrapType(<any>types[typeName], config);
}
} |