Chart component. Update web utils.
This commit is contained in:
1 parent
f947c7770b
commit
590a70c2ff
6 files changed
+159
-8
No files matched your search
Vendored
+111
@@ -0,0 +1,111 @@
|
||||
import React, { useState, useMemo, useRef, useEffect } from 'react';
|
||||
import ChartJS from 'chart.js';
|
||||
import { format, subDays, subHours, startOfHour } from 'date-fns';
|
||||
import { get } from 'lib/web';
|
||||
|
||||
export default function Chart({ websiteId, startDate, endDate }) {
|
||||
const [data, setData] = useState();
|
||||
const canvas = useRef();
|
||||
const chart = useRef();
|
||||
const metrics = useMemo(() => {
|
||||
if (data) {
|
||||
const points = {};
|
||||
const now = startOfHour(new Date());
|
||||
|
||||
for (let i = 0; i <= 168; i++) {
|
||||
const d = new Date(subHours(now, 168 - i));
|
||||
const key = format(d, 'yyyy-MM-dd-HH');
|
||||
points[key] = { t: startOfHour(d).toISOString(), y: 0 };
|
||||
}
|
||||
|
||||
data.pageviews.forEach(e => {
|
||||
const key = format(new Date(e.created_at), 'yyyy-MM-dd-HH');
|
||||
points[key].y += 1;
|
||||
});
|
||||
|
||||
return points;
|
||||
}
|
||||
}, [data]);
|
||||
console.log(metrics);
|
||||
|
||||
async function loadData() {
|
||||
setData(
|
||||
await get(`/api/website/${websiteId}/pageviews`, {
|
||||
start_at: startDate,
|
||||
end_at: endDate,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function draw() {
|
||||
if (!chart.current && canvas.current) {
|
||||
chart.current = new ChartJS(canvas.current, {
|
||||
type: 'bar',
|
||||
data: {
|
||||
datasets: [
|
||||
{
|
||||
label: 'page views',
|
||||
data: Object.values(metrics),
|
||||
lineTension: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
options: {
|
||||
animation: {
|
||||
duration: 300,
|
||||
},
|
||||
tooltips: {
|
||||
intersect: false,
|
||||
},
|
||||
hover: {
|
||||
animationDuration: 0,
|
||||
},
|
||||
scales: {
|
||||
xAxes: [
|
||||
{
|
||||
type: 'time',
|
||||
distribution: 'series',
|
||||
time: {
|
||||
unit: 'hour',
|
||||
displayFormats: {
|
||||
hour: 'ddd M/DD',
|
||||
},
|
||||
tooltipFormat: 'ddd M/DD hA',
|
||||
},
|
||||
ticks: {
|
||||
autoSkip: true,
|
||||
minRotation: 0,
|
||||
maxRotation: 0,
|
||||
maxTicksLimit: 7,
|
||||
},
|
||||
},
|
||||
],
|
||||
yAxes: [
|
||||
{
|
||||
ticks: {
|
||||
beginAtZero: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (metrics) {
|
||||
draw();
|
||||
}
|
||||
}, [metrics]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<canvas ref={canvas} width={960} height={400} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,7 +11,7 @@ export const prisma = new PrismaClient({
|
||||
|
||||
prisma.on('query', e => {
|
||||
if (process.env.LOG_QUERY) {
|
||||
console.log(`${e.query} (${e.duration}ms)`);
|
||||
console.log(`${e.params} -> ${e.query} (${e.duration}ms)`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -113,11 +113,15 @@ export async function getAccount(username = '') {
|
||||
);
|
||||
}
|
||||
|
||||
export async function getPageviews(website_id) {
|
||||
export async function getPageviews(website_id, start_at, end_at) {
|
||||
return runQuery(
|
||||
prisma.pageview.findMany({
|
||||
where: {
|
||||
website_id,
|
||||
created_at: {
|
||||
gte: start_at,
|
||||
lte: end_at,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
+22
-4
@@ -1,13 +1,31 @@
|
||||
export const post = (url, params) =>
|
||||
export const apiRequest = (method, url, body) =>
|
||||
fetch(url, {
|
||||
method: 'post',
|
||||
method,
|
||||
cache: 'no-cache',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(params),
|
||||
}).then(res => (res.status === 200 ? res.json() : null));
|
||||
body,
|
||||
}).then(res => (res.ok ? res.json() : null));
|
||||
|
||||
function parseQuery(url, params) {
|
||||
const query =
|
||||
params &&
|
||||
Object.keys(params).reduce((values, key) => {
|
||||
if (params[key] !== undefined) {
|
||||
return values.concat(`${key}=${encodeURIComponent(params[key])}`);
|
||||
}
|
||||
return values;
|
||||
}, []);
|
||||
return query.length ? `${url}?${query.join('&')}` : url;
|
||||
}
|
||||
|
||||
export const get = (url, params) => apiRequest('get', parseQuery(url, params));
|
||||
|
||||
export const post = (url, params) => apiRequest('post', url, JSON.stringify(params));
|
||||
|
||||
export const del = (url, params) => apiRequest('del', parseQuery(url, params));
|
||||
|
||||
export const hook = (_this, method, callback) => {
|
||||
const orig = _this[method];
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { getPageviews } from 'lib/db';
|
||||
|
||||
export default async (req, res) => {
|
||||
console.log(req.query);
|
||||
const { id, start_at, end_at } = req.query;
|
||||
|
||||
const pageviews = await getPageviews(+id, new Date(+start_at), new Date(+end_at));
|
||||
|
||||
res.status(200).json({ pageviews });
|
||||
};
|
||||
+9
-1
@@ -2,6 +2,7 @@ import React from 'react';
|
||||
import Link from 'next/link';
|
||||
import cookies from 'next-cookies';
|
||||
import Layout from 'components/Layout';
|
||||
import Chart from 'components/Chart';
|
||||
import { verifySecureToken } from 'lib/crypto';
|
||||
|
||||
export default function HomePage({ username }) {
|
||||
@@ -10,6 +11,13 @@ export default function HomePage({ username }) {
|
||||
<h2>
|
||||
You've successfully logged in as <b>{username}</b>.
|
||||
</h2>
|
||||
<div>
|
||||
<Chart
|
||||
websiteId={3}
|
||||
startDate={Date.now() - 1000 * 60 * 60 * 24 * 7}
|
||||
endDate={Date.now()}
|
||||
/>
|
||||
</div>
|
||||
<Link href="/logout">
|
||||
<a>Logout 🡒</a>
|
||||
</Link>
|
||||
@@ -25,7 +33,7 @@ export async function getServerSideProps(context) {
|
||||
|
||||
return {
|
||||
props: {
|
||||
username: payload.username,
|
||||
...payload,
|
||||
},
|
||||
};
|
||||
} catch {
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
!function(){"use strict";function e(e){var t=this.constructor;return this.then((function(n){return t.resolve(e()).then((function(){return n}))}),(function(n){return t.resolve(e()).then((function(){return t.reject(n)}))}))}var t=setTimeout;function n(e){return Boolean(e&&void 0!==e.length)}function r(){}function o(e){if(!(this instanceof o))throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],f(e,this)}function i(e,t){for(;3===e._state;)e=e._value;0!==e._state?(e._handled=!0,o._immediateFn((function(){var n=1===e._state?t.onFulfilled:t.onRejected;if(null!==n){var r;try{r=n(e._value)}catch(e){return void s(t.promise,e)}u(t.promise,r)}else(1===e._state?u:s)(t.promise,e._value)}))):e._deferreds.push(t)}function u(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var n=t.then;if(t instanceof o)return e._state=3,e._value=t,void a(e);if("function"==typeof n)return void f((r=n,i=t,function(){r.apply(i,arguments)}),e)}e._state=1,e._value=t,a(e)}catch(t){s(e,t)}var r,i}function s(e,t){e._state=2,e._value=t,a(e)}function a(e){2===e._state&&0===e._deferreds.length&&o._immediateFn((function(){e._handled||o._unhandledRejectionFn(e._value)}));for(var t=0,n=e._deferreds.length;t<n;t++)i(e,e._deferreds[t]);e._deferreds=null}function c(e,t,n){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof t?t:null,this.promise=n}function f(e,t){var n=!1;try{e((function(e){n||(n=!0,u(t,e))}),(function(e){n||(n=!0,s(t,e))}))}catch(e){if(n)return;n=!0,s(t,e)}}o.prototype["catch"]=function(e){return this.then(null,e)},o.prototype.then=function(e,t){var n=new this.constructor(r);return i(this,new c(e,t,n)),n},o.prototype["finally"]=e,o.all=function(e){return new o((function(t,r){if(!n(e))return r(new TypeError("Promise.all accepts an array"));var o=Array.prototype.slice.call(e);if(0===o.length)return t([]);var i=o.length;function u(e,n){try{if(n&&("object"==typeof n||"function"==typeof n)){var s=n.then;if("function"==typeof s)return void s.call(n,(function(t){u(e,t)}),r)}o[e]=n,0==--i&&t(o)}catch(e){r(e)}}for(var s=0;s<o.length;s++)u(s,o[s])}))},o.resolve=function(e){return e&&"object"==typeof e&&e.constructor===o?e:new o((function(t){t(e)}))},o.reject=function(e){return new o((function(t,n){n(e)}))},o.race=function(e){return new o((function(t,r){if(!n(e))return r(new TypeError("Promise.race accepts an array"));for(var i=0,u=e.length;i<u;i++)o.resolve(e[i]).then(t,r)}))},o._immediateFn="function"==typeof setImmediate&&function(e){setImmediate(e)}||function(e){t(e,0)},o._unhandledRejectionFn=function(e){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",e)};var l=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("unable to locate global object")}();"Promise"in l?l.Promise.prototype["finally"]||(l.Promise.prototype["finally"]=e):l["Promise"]=o,self.fetch||(self.fetch=function(e,t){return t=t||{},new Promise((function(n,r){var o=new XMLHttpRequest,i=[],u=[],s={},a=function(){return{ok:2==(o.status/100|0),statusText:o.statusText,status:o.status,url:o.responseURL,text:function(){return Promise.resolve(o.responseText)},json:function(){return Promise.resolve(JSON.parse(o.responseText))},blob:function(){return Promise.resolve(new Blob([o.response]))},clone:a,headers:{keys:function(){return i},entries:function(){return u},get:function(e){return s[e.toLowerCase()]},has:function(e){return e.toLowerCase()in s}}}};for(var c in o.open(t.method||"get",e,!0),o.onload=function(){o.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(e,t,n){i.push(t=t.toLowerCase()),u.push([t,n]),s[t]=s[t]?s[t]+","+n:n})),n(a())},o.onerror=r,o.withCredentials="include"==t.credentials,t.headers)o.setRequestHeader(c,t.headers[c]);o.send(t.body||null)}))});var h=function(e,t,n){var r=e[t];return function(){for(var t=[],o=arguments.length;o--;)t[o]=arguments[o];return n.apply(null,t),r.apply(e,t)}};!function(e,t){var n=e.screen,r=n.width,o=n.height,i=e.navigator.language,u=e.location,s=u.hostname,a=u.pathname,c=u.search,f=e.localStorage,l=e.document,p=e.history,d=l.querySelector("script[data-website-id]"),v=d&&d.getAttribute("data-website-id"),y=new URL(d.src).origin,m=r+"x"+o,w=[],_=""+a+c,g=l.referrer,b=function(e,n){var r={session:f.getItem(t),url:_,referrer:g,website:v,hostname:s,screen:m,language:i};return n&&Object.keys(n).forEach((function(e){r[e]=n[e]})),function(e,t){return fetch(e,{method:"post",cache:"no-cache",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(t)}).then((function(e){return 200===e.status?e.json():null}))}(y+"/api/collect",{type:e,payload:r}).then((function(e){var n=e.session;return n&&f.setItem(t,n)}))},j=Line truncated
|
||||
!function(){"use strict";function e(e){var t=this.constructor;return this.then((function(n){return t.resolve(e()).then((function(){return n}))}),(function(n){return t.resolve(e()).then((function(){return t.reject(n)}))}))}var t=setTimeout;function n(e){return Boolean(e&&void 0!==e.length)}function r(){}function o(e){if(!(this instanceof o))throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],f(e,this)}function i(e,t){for(;3===e._state;)e=e._value;0!==e._state?(e._handled=!0,o._immediateFn((function(){var n=1===e._state?t.onFulfilled:t.onRejected;if(null!==n){var r;try{r=n(e._value)}catch(e){return void s(t.promise,e)}u(t.promise,r)}else(1===e._state?u:s)(t.promise,e._value)}))):e._deferreds.push(t)}function u(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var n=t.then;if(t instanceof o)return e._state=3,e._value=t,void a(e);if("function"==typeof n)return void f((r=n,i=t,function(){r.apply(i,arguments)}),e)}e._state=1,e._value=t,a(e)}catch(t){s(e,t)}var r,i}function s(e,t){e._state=2,e._value=t,a(e)}function a(e){2===e._state&&0===e._deferreds.length&&o._immediateFn((function(){e._handled||o._unhandledRejectionFn(e._value)}));for(var t=0,n=e._deferreds.length;t<n;t++)i(e,e._deferreds[t]);e._deferreds=null}function c(e,t,n){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof t?t:null,this.promise=n}function f(e,t){var n=!1;try{e((function(e){n||(n=!0,u(t,e))}),(function(e){n||(n=!0,s(t,e))}))}catch(e){if(n)return;n=!0,s(t,e)}}o.prototype["catch"]=function(e){return this.then(null,e)},o.prototype.then=function(e,t){var n=new this.constructor(r);return i(this,new c(e,t,n)),n},o.prototype["finally"]=e,o.all=function(e){return new o((function(t,r){if(!n(e))return r(new TypeError("Promise.all accepts an array"));var o=Array.prototype.slice.call(e);if(0===o.length)return t([]);var i=o.length;function u(e,n){try{if(n&&("object"==typeof n||"function"==typeof n)){var s=n.then;if("function"==typeof s)return void s.call(n,(function(t){u(e,t)}),r)}o[e]=n,0==--i&&t(o)}catch(e){r(e)}}for(var s=0;s<o.length;s++)u(s,o[s])}))},o.resolve=function(e){return e&&"object"==typeof e&&e.constructor===o?e:new o((function(t){t(e)}))},o.reject=function(e){return new o((function(t,n){n(e)}))},o.race=function(e){return new o((function(t,r){if(!n(e))return r(new TypeError("Promise.race accepts an array"));for(var i=0,u=e.length;i<u;i++)o.resolve(e[i]).then(t,r)}))},o._immediateFn="function"==typeof setImmediate&&function(e){setImmediate(e)}||function(e){t(e,0)},o._unhandledRejectionFn=function(e){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",e)};var l=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("unable to locate global object")}();"Promise"in l?l.Promise.prototype["finally"]||(l.Promise.prototype["finally"]=e):l["Promise"]=o,self.fetch||(self.fetch=function(e,t){return t=t||{},new Promise((function(n,r){var o=new XMLHttpRequest,i=[],u=[],s={},a=function(){return{ok:2==(o.status/100|0),statusText:o.statusText,status:o.status,url:o.responseURL,text:function(){return Promise.resolve(o.responseText)},json:function(){return Promise.resolve(JSON.parse(o.responseText))},blob:function(){return Promise.resolve(new Blob([o.response]))},clone:a,headers:{keys:function(){return i},entries:function(){return u},get:function(e){return s[e.toLowerCase()]},has:function(e){return e.toLowerCase()in s}}}};for(var c in o.open(t.method||"get",e,!0),o.onload=function(){o.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(e,t,n){i.push(t=t.toLowerCase()),u.push([t,n]),s[t]=s[t]?s[t]+","+n:n})),n(a())},o.onerror=r,o.withCredentials="include"==t.credentials,t.headers)o.setRequestHeader(c,t.headers[c]);o.send(t.body||null)}))});var h=function(e,t){return function(e,t,n){return fetch(t,{method:e,cache:"no-cache",headers:{Accept:"application/json","Content-Type":"application/json"},body:n}).then((function(e){return e.ok?e.json():null}))}("post",e,JSON.stringify(t))},p=function(e,t,n){var r=e[t];return function(){for(var t=[],o=arguments.length;o--;)t[o]=arguments[o];return n.apply(null,t),r.apply(e,t)}};!function(e,t){var n=e.screen,r=n.width,o=n.height,i=e.navigator.language,u=e.location,s=u.hostname,a=u.pathname,c=u.search,f=e.localStorage,l=e.document,d=e.history,v=l.querySelector("script[data-website-id]"),y=v&&v.getAttribute("data-website-id"),m=new URL(v.src).origin,w=r+"x"+o,_=[],g=""+a+c,b=l.referrer,j=function(e,n){var r={session:f.getItem(t),url:g,referrer:b,website:y,hostname:s,screen:w,language:i};return n&&Object.keys(n).forEach((function(e){r[e]=n[e]})),h(m+"/api/collect",{type:e,payload:r}).then((function(e){var n=e.session;returnLine truncated
|
||||
Reference in new issue
Block a user