import { injectable , Interceptor , InvocationContext , InvocationResult , Provider , ValueOrPromise , } from '@loopback/core' ; import { CoffeeShop } from '../models' ; /**
 * This class will be bound to the application as an `Interceptor` during
 * `boot`
 */ @ injectable ( { tags : { key : ValidatePhoneNumInterceptor . BINDING_KEY } } ) export class ValidatePhoneNumInterceptor implements Provider < Interceptor > { static readonly BINDING_KEY = `interceptors.${ ValidatePhoneNumInterceptor . name }` ; returns value ( ) { return this . intercept . bind ( this ) ; } param invocationCtx param next async intercept ( invocationCtx , next ) { let coffeeShop ; if ( invocationCtx . methodName === 'create' ) coffeeShop = invocationCtx . args [ 0 ] ; else if ( invocationCtx . methodName === 'updateById' ) coffeeShop = invocationCtx . args [ 1 ] ; if ( coffeeShop && ! this . isAreaCodeValid ( coffeeShop . phoneNum , coffeeShop . city ) ) { const err = new ValidationError ( 'Area code and city do not match' ) ; err . statusCode = 400 ; throw err ; } const result = await next ( ) ; return result ; } isAreaCodeValid ( phoneNum , city ) { const areaCode = phoneNum . slice ( 0 , 3 ) ; if ( city . toLowerCase ( ) === 'toronto' ) return areaCode === '416' || areaCode === '647' ; return true ; } } class ValidationError extends Error { code ? : string ; statusCode ? : number ; }