Example #1
0
        private async Task <JObject> GetDataObject(ISkraprWorker worker)
        {
            var result = new JObject();

            foreach (var gatherProperty in Gather.Properties())
            {
                var propertyName = gatherProperty.Name;

                bool   awaitPromise = false;
                string gatherScript = null;
                switch (gatherProperty.Value.Type)
                {
                case JTokenType.String:
                    gatherScript = gatherProperty.Value.Value <string>();
                    break;

                case JTokenType.Object:
                    //TODO: Implement this -- objects can specify additional settings.
                    throw new NotImplementedException("Objects are not yet supported.");

                default:
                    throw new InvalidOperationException($"Unknown or invalid value for gather property {propertyName}: {gatherProperty.Value.Type}");
                }

                if (String.IsNullOrWhiteSpace(gatherScript))
                {
                    throw new InvalidOperationException($"A gather script must be specified for property {propertyName}");
                }

                var fnGatherScript   = $@"(function() {{
    'use strict';
    var result = {gatherScript}
    return JSON.stringify({{ result }});
}})();";
                var evaluateResponse = await worker.Session.Runtime.Evaluate(new Runtime.EvaluateCommand
                {
                    AwaitPromise          = awaitPromise,
                    Expression            = fnGatherScript,
                    IncludeCommandLineAPI = true,
                    ContextId             = worker.DevTools.CurrentFrameContext.Id,
                    ObjectGroup           = "Skrapr"
                });

                if (evaluateResponse.Result.Subtype == "error")
                {
                    throw new InvalidOperationException($"An error occurred while evaluating script on property '{propertyName}': {evaluateResponse.Result.Description}");
                }

                var strResult = evaluateResponse.Result.Value as string;
                if (strResult == null)
                {
                    throw new InvalidOperationException($"Unable to obtain the gather result for property {propertyName}");
                }

                var objResult = JToken.Parse(strResult);
                result.Add(propertyName, objResult["result"]);
            }

            return(result);
        }