GithubHelp home page GithubHelp logo

keen / keen-analysis.js Goto Github PK

View Code? Open in Web Editor NEW
40.0 25.0 15.0 4.3 MB

A light JavaScript client for Keen

Home Page: https://keen.io/docs/compute/

License: MIT License

JavaScript 99.69% HTML 0.31%
analytics keen-js analysis web-analytics analytics-api querying api-client caching

keen-analysis.js's Introduction

keen-analysis.js

A JavaScript Client for Keen.

Slack

Installation

Install this package from NPM Recommended

npm install keen-analysis --save

Public CDN

<script crossorigin src="https://cdn.jsdelivr.net/npm/keen-analysis@3/dist/keen-analysis.min.js"></script>

Project ID & API Keys

Login to Keen IO to create a project and grab the Project ID and Read Key from your project's Access page.

To run keen-analysis on your localhost you need to grab your access keys and update config.js file.

const demoConfig = {
  projectId: 'YOUR_PROJECT_ID',
  readKey: 'YOUR_READ_KEY',
  writeKey: 'YOUR_WRITE_KEY',
  masterKey: 'YOUR_MASTER_KEY',
};

Getting started

The following examples demonstrate how to get up and running quickly with our API. This SDK can also contains basic HTTP wrappers that can be used to interact with every part of our platform.

If any of this is confusing, join our Slack community or send us a message.

Looking for tracking capabilities? Check out keen-tracking.js.

Upgrading from an earlier version of keen-js? Read this.

Setup and Running a Query

Create a new client instance with your Project ID and Read Key, and use the .query() method to execute an ad-hoc query. This client instance is the core of the library and will be required for all API-related functionality.

// Browsers
import KeenAnalysis from 'keen-analysis';

// Node.js
// const KeenAnalysis = require('keen-analysis');

const client = new KeenAnalysis({
  projectId: 'YOUR_PROJECT_ID',
  readKey: 'YOUR_READ_KEY'
});

client
  .query({
    analysisType: 'count',
    eventCollection: 'pageviews',
    timeframe: 'this_31_days'
  })
  .then(res => {
    // Handle results, e.g. visualise them with https://github.com/keen/keen-dataviz.js
  })
  .catch(err => {
    // Handle errors
  });

Important: the res response object returned in the example above will also include a query object containing the analysis_type and query parameters shaping the request. This query information is artificially appended to the response by this SDK, as this information is currently only provided by the API for saved queries. Why? Query parameters are extremely useful for intelligent response handling downstream, particularly by our own automagical visualization capabilities in keen-dataviz.js.

Async Await example

const getPageviews = async () => {
  try {
    const result = await client
      .query({
        analysisType: 'count',
        eventCollection: 'pageviews',
        timeframe: 'this_31_days'
      });
    console.log('Result', result);
    return result;
  } catch (error) {
    console.log('Error', error);
  }
}

Cache queries in the client

Client-side (browser) caching is based on IndexedDB API.

import KeenAnalysis from 'keen-analysis';

// set global caching of all queries *Optional*
const client = new KeenAnalysis({
  projectId: 'YOUR_PROJECT_ID',
  masterKey: 'YOUR_MASTER_KEY',
  cache: {
    maxAge: 60 * 1000 // cache for 1 minute
  }
});

// or set custom caching for a specific query *Optional*
client
  .query({
    analysisType: 'count',
    eventCollection: 'pageviews',
    timeframe: 'this_31_days',
    cache: {
      maxAge: 10 * 1000 // [ms]
    }
  })
  .then(res => {
    // Handle results
  })
  .catch(err => {
    // Handle errors
  });

// don't cache a specific query, even if the global caching is on
client
  .query({
    analysisType: 'count',
    eventCollection: 'pageviews',
    timeframe: 'this_14_days',
    cache: false
  })
  .then(res => {
    // Handle results
  })
  .catch(err => {
    // Handle errors
  });

Local Queries

The Local Query Experimental Feature allows you to run queries on already browser-side-cached or file-stored data. This feature is available only in the NPM version of the library.

Local Query on the browser cache

import KeenAnalysis from 'keen-analysis';
import localQuery from 'keen-analysis/dist/modules/localQuery';

client
  .query({
    analysisType: 'extraction', // IMPORTANT
    eventCollection: 'pageviews',
    timeframe: 'this_30_days',
    cache: {
      // cache the result in the browser for 1 day
      maxAge: 1000 * 60 * 60 * 24
    }
  })
  .then(responseJSON => {
    localQuery({
        data: responseJSON,

        // now run any query that you would normally run
        // for example
        analysisType: 'count',
        timeframe: 'this_7_days',

        debug: true // OPTIONAL: see the details of each query in your console
      })
      .then(localQueryResponseJSON => {
        // handle results, for example pass them to keen-dataviz
      })
      .catch(localQueryError => {
        console.log(localQueryError);
      });
  });

Local Query on the file

import localQuery from 'keen-analysis/dist/modules/localQuery';

localQuery({
    file: 'dummy-data.csv', // .csv or .json file

    analysisType: 'count',
    timeframe: 'this_14_days'
  })
  .then(localQueryResponseJSON => {
    // handle results
  })
  .catch(localQueryError => {
    // handle error
  });

The Local Query configuration

localQuery({
    /*
      Define the data source
      The Local Query accepts all of the Extraction query results
    */
    data: responseJSON, // response from the Browser's cache or Keen's API
    // OR
    file: 'dummy-data.csv', // .csv or .json files

    /*
      Use standard query parameters - https://keen.io/docs/api/#analyses
    */
    analysisType: 'count',
    timeframe: 'this_7_days', // optional
    // filter, interval, limit etc...

    /*
      Optional
    */
    debug: true, // see the details of each query in your console
    onOutOfTimeframeRange: () => {}, // load more data from API or ignore
  })
  .then(localQueryResponseJSON => {
    // handle results
  })
  .catch(localQueryError => {
    // handle error
  });

Local Query in the Node.js environment

const KeenAnalysis = require('keen-analysis');
// import from Node.js modules:
const localQuery = require('keen-analysis/dist/node/modules/localQuery').default;

Create a Saved Query

API reference: Saved Query

import KeenAnalysis from 'keen-analysis';

const client = new KeenAnalysis({
  projectId: 'YOUR_PROJECT_ID',
  masterKey: 'YOUR_MASTER_KEY'
});

// Create or Update a saved query
client
  .put({
    url: client.url('queries', 'saved', 'daily-pageviews-this-14-days'),
    api_key: client.config.masterKey,
    params: {
      refreshRate: 60 * 60 * 4, // API will refresh result of this query every 4 hours
      query: {
        analysisType: 'count',
        eventCollection: 'pageviews',
        timeframe: 'this_14_days'
      },
      metadata: {
        displayName: 'Daily pageviews (this 14 days)',
        /*
          If you plan to use this saved query inside Explorer set the default visualization.
          We suggest using "metric" for a single value, "area" for intervals
        */
        visualization: {
          chartType: "metric"
        }
      }
    }
  })
  .then(res => {
    // Handle results
  })
  .catch(err => {
    // Handle errors
  });

Read Saved/Cached Queries

import KeenAnalysis from 'keen-analysis';

const client = new KeenAnalysis({
  projectId: 'YOUR_PROJECT_ID',
  readKey: 'YOUR_READ_KEY'
});

// read already saved query
client
  .query({
    savedQueryName: 'pageviews-this-14-days'
  })
  .then(res => {
    // Handle results
  })
  .catch(err => {
    // Handle errors
  });

List Saved Queries

import KeenAnalysis from 'keen-analysis';

const client = new KeenAnalysis({
  projectId: 'YOUR_PROJECT_ID',
  masterKey: 'YOUR_MASTER_KEY'
});

// Retrieve all saved queries
client
  .get({
    url: client.url('queries', 'saved'),
    api_key: client.config.masterKey
  })
  .then(res => {
    // Handle results
  })
  .catch(err => {
    // Handle errors
  });

Create Cached Datasets

import KeenAnalysis from 'keen-analysis';

const client = new KeenAnalysis({
  projectId: 'PROJECT_ID',
  masterKey: 'MASTER_KEY'
});

const newDatasetName = 'my-first-dataset';

client
  .put({
    url: client.url('datasets', newDatasetName),
    api_key: client.config.masterKey,
    params: {
      displayName: 'Count Daily Product Purchases Over $100 by Country',
      query: {
        analysisType: 'count',
        eventCollection: 'purchases',
        filters: [
          {
            propertyName: 'price',
            operator: 'gte',
            propertyValue: 100
          }
        ],
        groupBy: 'ip_geo_info.country',
        interval: 'daily',
        timeframe: 'this_500_days'
      },
      indexBy: 'product.id'
    }
  })
  .then(res => {
    console.log('res', res);
    // Handle response
  })
  .catch(err => {
    // Handle error
  });

Read Cached Datasets

import KeenAnalysis from 'keen-analysis';

const client = new KeenAnalysis({
  projectId: 'YOUR_PROJECT_ID',
  readKey: 'YOUR_READ_KEY'
});

client
  .query({
    datasetName: 'my-cached-dataset',
    indexBy: 'customer.id',
    timeframe: 'this_7_days'
  })
  .then(res => {
    // Handle results
  })
  .catch(err => {
    // Handle errors
  });

Cancel query

import KeenAnalysis from 'keen-analysis';

const client = new KeenAnalysis({
  projectId: 'YOUR_PROJECT_ID',
  readKey: 'YOUR_READ_KEY'
});

const queryPageviews = client.query({
  analysisType: 'count',
  eventCollection: 'pageviews',
  timeframe: 'this_31_days'
});

// cancel
queryPageviews.abort();

/*
query.then(res => {
  console.log(res);
  })
  .catch(err => {
    console.log(err);
  });
*/

Timeout of the queries

Fetch API doesn't support timeout, but we can fix that

import KeenAnalysis from 'keen-analysis';

const client = new KeenAnalysis({
  projectId: 'YOUR_PROJECT_ID',
  readKey: 'YOUR_READ_KEY'
});

const queryPageviews = client.query({
  analysisType: 'count',
  eventCollection: 'pageviews',
  timeframe: 'this_31_days'
});

// cancel after 10 seconds
setTimeout(() => {
  queryPageviews.abort();
}, 1000 * 10);

queryPageviews
  .then(res => {
    console.log('response', res);
  })
  .catch(err => {
    console.log('error', err);
  });

Running multiple queries at once

client.run() will Promise.all array of queries. Please note, that in general, we recommend running queries independently of each other. This example is useful if you are rendering many results on one Keen-dataviz.js chart object.

import KeenAnalysis from 'keen-analysis';

const client = new KeenAnalysis({
  projectId: 'YOUR_PROJECT_ID',
  readKey: 'YOUR_READ_KEY'
});

const queryPageviews = client.query({
  analysisType: 'count',
  eventCollection: 'pageviews',
  timeframe: 'this_14_days'
});

const queryFormSubmissions = client.query({
  analysisType: 'count',
  eventCollection: 'form_submissions',
  timeframe: 'this_14_days'
});

// promise all
client
  .run([queryPageviews, queryFormSubmissions])
  .then(res => {
    // Handle results
  })
  .catch(err => {
    // Handle errors
  });

Parsing query results

resultParsers is an array of functions and the response from API will be parsed by each function.

import KeenAnalysis from 'keen-analysis';

const client = new KeenAnalysis({
  projectId: 'YOUR_PROJECT_ID',
  readKey: 'YOUR_READ_KEY',
  resultParsers: [
    (value) => {
      return Math.round(value); // or eg. value.toPrecision(2)
    }
  ]
});

client.query({
  analysisType: 'count',
  eventCollection: 'pageviews',
  timeframe: 'this_3_months'
  })
  .then(res => {
    // Handle results
  })
  .catch(err => {
    // Handle errors
  });

Optimise queries

Read the execution metadata to optimise queries and reduce your bill.

client.query({
  analysisType: 'count',
  eventCollection: 'pageviews',
  timeframe: 'this_3_months',
  includeMetadata: true
  })
  .then(res => {
    // Handle results
  })
  .catch(err => {
    // Handle errors
  });

For multiple queries you can define includeMetadata in client constructor and this will be propagated to all queries.

import KeenAnalysis from 'keen-analysis';

const client = new KeenAnalysis({
  projectId: 'YOUR_PROJECT_ID',
  readKey: 'YOUR_READ_KEY',
  includeMetadata: true,
});

Custom Host

You can set a custom domain for requests

const client = new KeenAnalysis({
  projectId: 'PROJECT_ID',
  readKey: 'YOUR_READ_KEY',
  host: 'somehost.com'
});

Client instance methods

The following HTTP methods are exposed on the client instance:

  • .get(object)
  • .post(object)
  • .put(object)
  • .del(object)

These HTTP methods take a single argument and return a promise for the asynchronous response.


CamelCase conversion

All of the parameters provided in the camelCase format will be automatically converted into an API-digestible under_score format.


Upgrading from keen-js

There are several breaking changes from earlier versions of keen-js.

  • All new HTTP methods: keen-js supports generic HTTP methods (.get(), .post(), .put(), and .del()) for interacting with various API resources. The new Promise-backed design of this SDK necessitated a full rethinking of how these methods behave.
  • Keen.Request object has been removed: this object is no longer necessary for managing query requests.
  • Redesigned implementation of client.url(): This method previously included https://api.keen.io/3.0/projects/PROJECT_ID plus a path argument ('/events/whatever'). This design severely limited its utility, so we've revamped this method.

This method now references an internal collection of resource paths, and constructs URLs using client configuration properties like host and projectId:

const url = client.url('projectId');
// Renders {protocol}://{host}/3.0/projects/{projectId}
// Returns https://api.keen.io/3.0/projects/PROJECT_ID

Default resources:

  • 'base': '{protocol}://{host}',
  • 'version': '{protocol}://{host}/3.0',
  • 'projects': '{protocol}://{host}/3.0/projects',
  • 'projectId': '{protocol}://{host}/3.0/projects/{projectId}',
  • 'queries': '{protocol}://{host}/3.0/projects/{projectId}/queries'
  • 'datasets': '{protocol}://{host}/3.0/projects/{projectId}/datasets'

Non-matching strings will be appended to the base resource, like so:

const url = client.url('/3.0/projects');
// Returns https://api.keen.io/3.0/projects

You can also pass in an object to append a serialized query string to the result, like so:

const url = client.url('events', { api_key: 'YOUR_API_KEY' });
// Returns https://api.keen.io/3.0/projects/PROJECT_ID/events?api_key=YOUR_API_KEY

Resources can be returned or added with the client.resources() method, like so:

client.resources()
// Returns client.config.resources object

client.resources({
  'new': '{protocol}://analytics.mydomain.com/my-custom-endpoint/{projectId}'
});
client.url('new');
// Returns 'https://analytics.mydomain.com/my-custom-endpoint/PROJECT_ID'

Contributing

This is an open source project and we love involvement from the community! Hit us up with pull requests and issues.

Learn more about contributing to this project.


Support

Need a hand with something? Shoot us an email at [email protected]. We're always happy to help, or just hear what you're building! Here are a few other resources worth checking out:


Custom builds

Run the following commands to install and build this project:

# Clone the repo
$ git clone https://github.com/keen/keen-analysis.js.git && cd keen-analysis.js

# Install project dependencies
$ npm install

# Build project with Webpack
$ npm run build

# Build and launch to view demo page
$ npm run start

# Run Jest tests
$ npm run test

keen-analysis.js's People

Contributors

adamkasprowicz avatar dariuszlacheta avatar dorkusprime avatar dustinlarimer avatar jtfell avatar maciejrybaniec avatar stof avatar venil7 avatar woahdae avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

keen-analysis.js's Issues

NPM install doesn't have a dist directory

I just tried installing 1.3.0 of this library using NPM.

After the installation, my directory only contained the following:

CHANGELOG.md LICENSE README.md lib package.json

Not sure what's up here but it looks like there are files missing compared to the repo.

resultParsers - funnel and multi_analysis with NaNs

Result from the API is not an array, so the client doesn't recognise it as a valid response - and passes NaN.

Example:

// set resultParsers in the config eg
  demoConfig.resultParsers= [
    (value) => {
      return Math.round(value);
    }
  ]
  const client = new Keen(demoConfig);

  client
  .query({
    analysisType: 'multi_analysis',
    eventCollection: 'pageviews',
    analyses: {
      'unique users': {
        analysisType: 'count_unique',
        targetProperty: 'keen.id',
      },
      'total visits': {
        analysisType: 'count',
      }
    },
    timeframe: 'this_1117_days',
  })
  .then(res => {
    // Handle results
    console.log(res);
  })
  .catch(err => {
    // Handle errors
    console.log(err);
  });

response from the API:

{"result": {"total visits": 22, "unique users": 22}}

response in the client:

{
query: { ... } // some pops,
result: NaN
}

SyntaxError thrown when no content returned by Keen API

Using the Keen.io API to delete a property for an event ( https://keen.io/docs/api/?javascript#delete-a-property ) returns a 204 - No Content result with no data sent (as expected). An attempt is still made to parse the data as JSON ( https://github.com/keen/keen-analysis.js/blob/master/lib/utils/http-server.js#L47 ), which fails and throws a SyntaxError. We are currently working around this issue by catching and ignoring that error, but this is a case that should be handled properly by the http client in keen-analysis.js instead.

Environment: Node v8.9.4

When not configured correctly, queries still try to run and return a weird error

I accidentally provided empty credentials (undefined) to the constructor of KeenAnalysis. Stupid of me. In any case, the error message I got was really confusing until I found the mistake. Would be nice if the constructor can check the given credentials and throw an error if it fails.

const KeenAnalysis = require("keen-analysis");
const KeenClient = new KeenAnalysis({
 projectId: Config.keen.projectId,   // was undefined
 readKey: Config.keen.readKey        // was undefined
});

The error I got from Keen when using KeenClient.query( ... ):

error: "value" required in setHeader("Authorization", value) {"stack":"Error: \"value\" required in setHeader(\"Authorization\", value)
    at validateHeader (_http_outgoing.js:489:11)
    at ClientRequest.setHeader (_http_outgoing.js:498:3)
    at new ClientRequest (_http_client.js:183:14)
    at Object.request (http.js:38:10)
    at Object.request (https.js:245:15)
    at Object.request (/app/node_modules/agent-base/patch-core.js:23:20)
    at request (/app/node_modules/keen-analysis/dist/node/webpack:/lib/utils/http-server.js:36:21)
    at httpHandler (/app/node_modules/keen-analysis/dist/node/webpack:/lib/request.js:105:27)
    at new Promise (<anonymous>)
    at request.send (/app/node_modules/keen-analysis/dist/node/webpack:/lib/request.js:98:26)
    at request.send (/app/node_modules/keen-analysis/dist/node/webpack:/lib/request.js:40:17)
    at Client.post [as query] (/app/node_modules/keen-analysis/dist/node/webpack:/lib/index.js:104:8)

Polyfills should be loaded separately

It would be great if a build bundle could be provided with no polyfills included (I'm thinking about the Promise and fetch polyfill here). We could have a file including polyfills and the other entrypoint to create a full bundle for easy consumption (or polyfills can be always expected externally, but that would require a major version bump).
In my project, I'm already loading polyfills for them, so it makes no sense to load them again when loading keen-analysis. That only increase the size of the JS.

SSL certification warning

Chrome is throwing SSL warning for Symantec cert:

The SSL certificate used to load resources from https://d26b395fwzu5fz.cloudfront.net will be distrusted in M70. Once distrusted, users will be prevented from loading these resources. See https://g.co/chrome/symantecpkicerts for more information.

Not sure if this is a Keen IO config or a Cloudfront one, but wanted to get it out there so it doesn't sneak up on your team.

`npm run start` fails

Contributing guidelines say to run npm run start, but I get the following. It looks to me like a step is missing, like downloading a "demo-config" project?

[git/master-]:keen-analysis.js% npm run start

> [email protected] start /Users/woody/Src/keen-analysis.js
> NODE_ENV=development webpack-dev-server

internal/modules/cjs/loader.js:626
    throw err;
    ^

Error: Cannot find module '../demo-config'
Require stack:
- /Users/woody/Src/keen-analysis.js/webpack.config.js
- /Users/woody/Src/keen-analysis.js/node_modules/webpack-cli/bin/convert-argv.js
- /Users/woody/Src/keen-analysis.js/node_modules/webpack-dev-server/bin/webpack-dev-server.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:623:15)
    at Function.Module._load (internal/modules/cjs/loader.js:527:27)
    at Module.require (internal/modules/cjs/loader.js:681:19)
    at require (internal/modules/cjs/helpers.js:16:16)
    at Object.<anonymous> (/Users/woody/Src/keen-analysis.js/webpack.config.js:14:22)
    at Module._compile (internal/modules/cjs/loader.js:774:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
    at Module.load (internal/modules/cjs/loader.js:641:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Module.require (internal/modules/cjs/loader.js:681:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/woody/Src/keen-analysis.js/webpack.config.js',
    '/Users/woody/Src/keen-analysis.js/node_modules/webpack-cli/bin/convert-argv.js',
    '/Users/woody/Src/keen-analysis.js/node_modules/webpack-dev-server/bin/webpack-dev-server.js'
  ]
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `NODE_ENV=development webpack-dev-server`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/woody/.npm/_logs/2020-05-13T00_40_14_982Z-debug.log

two queries at the same time

If make two keen-analysis.js queries at the same time, one which has sortBy+groupBy+interval, and the other which just has groupBy, the keen-analysis library seems to mix up the "options" for the two requests and parse one or the other incorrectly and crash.

Content update: Delete requests must pass parameters instead of content body

https://keen.io/docs/api/?shell#delete-events

Warning: Risk of data loss. You must pass your DELETE request timeframe and filters as query string parameters. Unlike other API requests, DELETE method does NOT support a content body. The content body will be ignored. Putting filters in the content body will result in your entire collection being inadvertently deleted. Using improper encoding or syntax in your filters can also cause them to be ignored, so please test your code before switching to the DELETE method.

Multiqueries problem

When multiqueries run with the same analysis_type for the same event_collection, both names are equal and this is causing problems with keen-dataviz.

Comparison analysis

It would be really nice if the keen SDK could handle comparison analysis. For example, sum of some property each day this month compared to last month where day [x] from this month sits right next to day[x] from last month. Or, the same comparison for each day this week vs. last week. Or, by hour with today vs. yesterday. I mocked up an excel version attached below.

I realize I can fire off 2 queries, merge the data in javascript, and run that into a chart. Just seems like this is something that could be useful to a lot of people and the community would be benefited by having this feature built in.

Also, I've been in touch with one of the keen support folks via Slack. They've been very helpful and suggested I store additional properties with my event data (ie, day of week, day of month, hour, etc.). I'm doing that now and it kind of works but not straightforward, takes some work, and doesn't produce the same result as the chart below.

untitled

Meteor loads incorrect HTTP handler, ignores object form of the "browser" field in package.json

Keen's CORS restrictions don't seem to allow the use of this library from the browser when added in npm package form to a Meteor application.

If the script is served from the Keen CDN, as documented here โ€“ you'd need to use the kadira:dochead package to add the script dynamically โ€“ all works fine, but then you don't appear to need this package installed. There are some obvious benefits to using the npm version in terms of version control and dependency management.

Is this by design, for security reasons, or am I perhaps missing something?

To reproduce this behavior, follow these steps:

  1. Install Meteor.

    curl https://install.meteor.com/ | sh
  2. From command line, create a new Meteor project.

    meteor create myapp
    cd myapp
  3. Add the keen-analysis package and start your app.

    meteor npm install keen-analysis --save
    meteor npm start

    Note that Meteor packages the keen-analysis scripts and serves them to the browser. The Keen object is then available for any browser-based code to execute.

  4. Add the following code to client/main.js:

    // client/main.js
    Template.hello.onRendered(() => {
      const client = new Keen();
      client
        .projectId('<PROJECT_ID>')
        .post(client.url('queries', 'count'))
        .auth('<READ_KEY>')
        .send({
          event_collection: '<MY_COLLECTION>',
          timeframe: 'this_14_days'
        })
        .then(res => console.log('results!', res))
        .catch(err => console.error('error!', err));
    });
  5. Hit http://localhost:3000.

    Observe via Chrome's developer tools that the query request is rejected due to a CORS preflighting issue.

    Response to preflight request doesn't pass access control check: A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.

  6. Using kadira:dochead, using the CDN version works fine:

    meteor add kadira:dochead
    // client/main.js
    // import Keen from 'keen-analysis';
    import { DocHead } from 'meteor/kadira:dochead';
    
    .
    .
    .
    Template.hello.onRendered(() => {
      const keenScript = 'https://d26b395fwzu5fz.cloudfront.net/keen-analysis-1.1.0.js';
      DocHead.loadScript(keenScript, () => {
        // do the stuff with Keen, it works...
      });
    });

Multi-analysis queries on the same event_collection problem

When running multiple queries with the same analysis_type on the same event_collection, second query is overwriting first one because both names are the same.

Solution:
Change the name of the next queries to not overwrite the first ones.

Split localQuery to a separate npm package

This package currently contains an experimental localQuery module, which is not included in the CDN bundle due to its size.
AFAICT, this module is not sharing any code with other parts of the package, and most of the dependencies of the package are actually dependencies of the localQuery module. Splitting this module into a separate NPM package would allow managing these deps better.

Bundle files should be optimized

When using webpack or rollup, the dist/node/keen-analysis.js file is used.

But this file is built with webpack in development mode, and so without the ModuleConcatenationPlugin. This has a big impact on the file size, and that's not something that webpack can optimize later (it does not have optimizations able to recognize a bundle generated by webpack to re-optimize it later).

math round values

Add ability to parse response to rounded numbers

average query and chart display - is it possible to round the values that are returned from the query
I am running a query for selecting average users per week. So decimal points are bad.

include metadata config option

if you initialize our lib with

const client = new KeenAnalysis({
  projectId: 'YOUR_PROJECT_ID',
  readKey: 'YOUR_READ_KEY',
  includeMetadata: true,
});

the response of each of the queries that you'll run should contain metadata informations

native app root.location.protocol undefined

I am trying to integrate keen with react-native app.
But I am not able to access any methods.
import Keen from 'keen-analysis';

var client = new Keen({ projectId: 'dummy', writeKey: 'dummy' }); console.log(client);

client object gets consoled.

client
  .query('count', {
    event_collection: 'sampleData',
    timeframe: 'this_14_days'
  })
  .then(res => {
    // Handle results
    console.log("queryResult::",res );
  })
  .catch(err => {
    // Handle errors
    console.log("err::",err);
  });

But this gives error as :
err:: [TypeError: undefined is not an object (evaluating 'root.location.protocol')]

Need help on this.

Cached Datasets

I have a use case that would fit cached datasets perfectly. The problem is that I'm using the keen-analysis library and need to keep the cached dataset usage in sync with the queries run ad-hoc (as some custom logic will operate on both sets of results). Therefore I need to reuse the Keen.Query declarations to define some cached datasets.

My questions:

a) Is there any cached dataset support in keen-analysis or is it planned in the near future?
b) If there isn't, can I get some pointers on how to go about adding it that would be likely to be merged?

camelCase query params

Keen's API uses underscore for property names, so right now keen-analysis client makes queries like this:

client
      .query({
        analysis_type: 'count',
        event_collection: 'pageviews',
        timeframe: 'this_31_days'
      });

it's fine as long as you don't use Linter on your .js files.
Let's add ability to use camelCase property names inside .query:

client
      .query({
        analysisType: 'count',
        eventCollection: 'pageviews',
        timeframe: 'this_31_days'
      });

and let keen-analysis do the mapping from camelCase to underscores just before sending the request to the API

Filter timeframe with saved query

Is there a way of reducing the timeframe for a saved query? So if the query is for 14 days can I ask the library to filter it down to 7 days like I can for a cached dataset.

@types/keen-analysis not found

Working with React in TypeScript, the application doesn't understand the types so webpack recommend me to install the library. This problem appears when I try to import keen-analysis

import KeenAnalysis from 'keen-analysis';
Could not find a declaration file for module 'keen-analysis'. '/Users/../Projects/envoy/.../node_modules/keen-analysis/dist/node/keen-analysis.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/keen-analysis` if it exists or add a new declaration (.d.ts) file containing `declare module 'keen-analysis';`

So I tried to install @types/keen-analysis, but npm says that this library doesn't exist? are there any library to type keen-analysis?

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@types%2fkeen-analysis - Not found
npm ERR! 404 
npm ERR! 404  '@types/keen-analysis@latest' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404 
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

Expose an accessor-builder function for managing embedded client instances

This is a wild idea worth exploring: standardizing the creation and management of client instances embedded in higher-level applications, such as the Explorer and Dashboard apps. This could greatly reduce external dependencies, which often result in version conflicts and other surprising behavior.

Pseudo-code sketch:

// inside keen-analysis.js
var Keen.createClient = function (propName) {
  return function(obj){
    this[propName] = obj && obj !== null ? new Keen(obj) : undefined;
  };
};

// inside a custom app
var Keen = require('keen-analysis');
var myApp = function(){};

myApp.protoype.client = Keen.createClient('keenClient');
// curries a custom accessor bah-zam!

External dependencies should not be bundled in the localQuery module

As the dependencies (on moment and a few others) are declared in the package.json, they should not be bundled in the file (at least for the node output) but be treated as externals instead.
This way, bundlers like webpack or rollup would import them from their location and be able to dedupe them. When they are bundled, they don't know about the fact that most of the code is actually from moment.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.