func buildFetchProjector()

in wstl1/mapping_engine/fetch/fetch.go [51:110]


func buildFetchProjector(ctx context.Context, httpQuery *httppb.HttpFetchQuery) (types.Projector, error) {
	return func(arguments []jsonutil.JSONMetaNode, pctx *types.Context) (jsonutil.JSONToken, error) {
		errLocation := errors.FnLocationf("Fetch Function Preamble %q", httpQuery.GetName())

		requestMethodNode, err := mapping.EvaluateValueSource(httpQuery.GetRequestMethod(), arguments, nil, pctx, jsonutil.DefaultAccessor{})
		if err != nil {
			return nil, errors.Wrap(errLocation, fmt.Errorf("error occurred in getting request method %s", err))
		}
		requestURLNode, err := mapping.EvaluateValueSource(httpQuery.GetRequestUrl(), arguments, nil, pctx, jsonutil.DefaultAccessor{})
		if err != nil {
			return nil, errors.Wrap(errLocation, fmt.Errorf("error occurred in getting request url %s", err))
		}

		requestURL, err := jsonutil.NodeToToken(requestURLNode)
		if err != nil {
			return nil, errors.Wrap(errLocation, err)
		}

		url, ok := requestURL.(jsonutil.JSONStr)
		if !ok {
			return nil, errors.Wrap(errLocation, fmt.Errorf("request url should be a string"))
		}

		requestMethod, err := jsonutil.NodeToToken(requestMethodNode)
		if err != nil {
			return nil, errors.Wrap(errLocation, err)
		}

		method, ok := requestMethod.(jsonutil.JSONStr)
		if !ok {
			return nil, errors.Wrap(errLocation, fmt.Errorf("request method should be a string"))
		}

		if strings.ToUpper(string(method)) != http.MethodGet {
			return nil, errors.Wrap(errLocation, fmt.Errorf("only GET method is supported"))
		}

		errLocation = errors.FnLocationf("Fetch Function %q", httpQuery.GetName())

		client := auth.NewClient(ctx)
		req, err := http.NewRequest(http.MethodGet, string(url), nil)
		if err != nil {
			return nil, errors.Wrap(errLocation, fmt.Errorf("error building new request %v", err))
		}
		q := req.URL.Query()
		req.URL.RawQuery = q.Encode()
		resource, err := client.ExecuteRequest(ctx, req, "search resources", false)

		if err != nil {
			return nil, errors.Wrap(errLocation, fmt.Errorf("error searching for resources %v", err))
		}

		jc := &jsonutil.JSONContainer{}
		if err := jc.UnmarshalJSON(*resource); err != nil {
			return nil, errors.Wrap(errLocation, fmt.Errorf("error parsing retrieved resources %s", err))
		}

		return *jc, nil
	}, nil
}