import { IRequestOptions } from "@esri/arcgis-rest-request" ; import { IField , IFeature , ILayerDefinition } from "@esri/arcgis-rest-types" ; import { IQueryFeaturesResponse } from "./query" ; import { getLayer } from "./getLayer" ; /**
 * Request options to fetch a feature by id.
 */ export interface IDecodeValuesOptions extends IRequestOptions { /**
     * Layer service url.
     */ url ? : string ; /**
     * Unique identifier of the feature.
     */ queryResponse : IQueryFeaturesResponse ; /**
     * * If a fieldset is provided, no internal metadata check will be issued to gather info about coded value domains.
     *
     * getFeatureService(url)
     *   .then(metadata => {
     *     queryFeatures({ url })
     *       .then(response => {
     *         decodeValues({
     *           url,
     *           queryResponse,
     *           fields: metadata.fields
     *         })
     *           .then(decodedResponse)
     *       })
     *   })
     */ fields ? : IField [ ] ; } param requestOptions returns export function decodeValues ( requestOptions ) { let prms ; if ( requestOptions . fields ) { prms = Promise . resolve ( requestOptions . fields ) ; } else { prms = getLayer ( { url : requestOptions . url } ) . then ( ( metadata ) => { return metadata . fields ; } ) ; } return prms . then ( ( fields ) => { const domains = extractCodedValueDomains ( fields ) ; if ( Object . keys ( domains ) . length < 1 ) { return requestOptions . queryResponse ; } const decodedFeatures = requestOptions . queryResponse . features . map ( ( feature ) => { const decodedAttributes = { } ; for ( const key in feature . attributes ) { if ( ! Object . prototype . hasOwnProperty . call ( feature . attributes , key ) ) continue ; const value = feature . attributes [ key ] ; const domain = domains [ key ] ; decodedAttributes [ key ] = value !== null && domain ? decodeValue ( value , domain ) : value ; } return { ... feature , ... { attributes : decodedAttributes } } ; } ) ; return { ... requestOptions . queryResponse , ... { features : decodedFeatures } , } ; } ) ; } function extractCodedValueDomains ( fields ) { return fields . reduce ( ( domains , field ) => { const domain = field . domain ; if ( domain && domain . type === "codedValue" ) { domains [ field . name ] = domain ; } return domains ; } , { } as { [ index ] : any ; } ) ; } function decodeValue ( value , domain ) { const codedValue = domain . codedValues . find ( ( d ) => { return value === d . code ; } ) ; return codedValue ? codedValue . name : value ; }