Skip to content

Commit

Permalink
Collection API.
Browse files Browse the repository at this point in the history
  • Loading branch information
mikecao committed Jul 18, 2020
1 parent f7f0c05 commit 11f1afe
Show file tree
Hide file tree
Showing 9 changed files with 400 additions and 64 deletions.
9 changes: 8 additions & 1 deletion components/layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,14 @@ export default function Layout({ title, children }) {
href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400&display=swap"
rel="stylesheet"
/>
<script async defer data-website-id="865234ad-6a92-11e7-8846-b05adad3f099" src="/umami.js" />
{typeof window !== 'undefined' && (
<script
async
defer
data-website-id="865234ad-6a92-11e7-8846-b05adad3f099"
src="/umami.js"
/>
)}
</Head>
<Header />
<main className="container">{children}</main>
Expand Down
3 changes: 2 additions & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export function parseCollectRequest(req) {

if (hash(`${website_id}${session_id}${time}`) === validationHash) {
return {
valid: true,
type,
session_id,
url,
Expand All @@ -68,5 +69,5 @@ export function parseCollectRequest(req) {
}
}

return null;
return { valid: false };
}
10 changes: 6 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.1.0",
"description": "Deliciously simple website analytics",
"main": "index.js",
"author": "Mike Cao",
"author": "Mike Cao <[email protected]>",
"license": "MIT",
"scripts": {
"dev": "next dev -p 8000",
Expand Down Expand Up @@ -33,15 +33,18 @@
"dotenv": "^8.2.0",
"next": "9.3.5",
"node-fetch": "^2.6.0",
"promise-polyfill": "^8.1.3",
"react": "16.13.1",
"react-dom": "16.13.1",
"request-ip": "^2.1.3",
"uuid": "^8.2.0",
"whatwg-fetch": "^3.2.0"
"unfetch": "^4.1.0",
"uuid": "^8.2.0"
},
"devDependencies": {
"@prisma/cli": "2.2.2",
"@rollup/plugin-buble": "^0.21.3",
"@rollup/plugin-node-resolve": "^8.4.0",
"@rollup/plugin-replace": "^2.3.3",
"@svgr/webpack": "^5.4.0",
"eslint": "^7.2.0",
"eslint-config-prettier": "^6.11.0",
Expand All @@ -57,7 +60,6 @@
"prettier": "^2.0.5",
"prettier-eslint": "^10.1.1",
"rollup": "^2.21.0",
"rollup-plugin-replace": "^2.2.0",
"rollup-plugin-terser": "^6.1.0",
"stylelint": "^13.6.0",
"stylelint-config-css-modules": "^2.2.0",
Expand Down
4 changes: 2 additions & 2 deletions pages/api/collect.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import { savePageView } from '../../lib/db';
export default async (req, res) => {
const values = parseCollectRequest(req);

if (values) {
if (values.valid) {
const { type, session_id, url, referrer } = values;

if (type === 'pageview') {
await savePageView(session_id, url, referrer);
}
}

res.status(200).json({ status: 'ok' });
res.status(200).json({ status: values.valid });
};
4 changes: 4 additions & 0 deletions pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ export default function Home() {
return (
<Layout>
Hello.
<br />
<a href="/?q=abc">abc</a>
<br />
<a href="/?q=123">123</a>
</Layout>
);
}
275 changes: 274 additions & 1 deletion public/umami.js

Large diffs are not rendered by default.

15 changes: 6 additions & 9 deletions rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
import 'dotenv/config';
import { terser } from 'rollup-plugin-terser';
import replace from 'rollup-plugin-replace';
import buble from '@rollup/plugin-buble';
import replace from '@rollup/plugin-replace';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import { terser } from 'rollup-plugin-terser';

export default {
input: 'scripts/umami/index.js',
output: {
file: 'public/umami.js',
format: 'iife',
globals: {
'detect-browser': 'detectBrowser',
'whatwg-fetch': 'fetch',
},
plugins: [terser()],
},
context: 'window',
plugins: [
nodeResolve(),
replace({
'process.env.UMAMI_URL': JSON.stringify(process.env.UMAMI_URL),
}),
nodeResolve(),
buble(),
terser({ compress: { evaluate: false } }),
],
};
41 changes: 27 additions & 14 deletions scripts/umami/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
import 'whatwg-fetch';
import 'promise-polyfill/src/polyfill';
import 'unfetch/polyfill';

const HOST_URL = process.env.UMAMI_URL;
const SESSION_VAR = 'umami.session';
const {
screen: { width, height },
navigator: { language },
location: { hostname, pathname, search },
localStorage: store,
document,
} = window;

function post(url, params) {
return fetch(url, {
Expand All @@ -7,33 +18,35 @@ function post(url, params) {
}).then(res => res.json());
}

(async () => {
const script = document.querySelector('script[data-website-id]');
const script = document.querySelector('script[data-website-id]');

if (script) {
const website_id = script.getAttribute('data-website-id');

if (website_id) {
const { width, height } = window.screen;
const { language } = window.navigator;
const { hostname, pathname, search } = window.location;
const referrer = window.document.referrer;
const referrer = document.referrer;
const screen = `${width}x${height}`;
const url = `${pathname}${search}`;

if (!window.localStorage.getItem('umami.session')) {
const session = await post(`${process.env.UMAMI_URL}/api/session`, {
if (!store.getItem(SESSION_VAR)) {
post(`${HOST_URL}/api/session`, {
website_id,
hostname,
url,
screen,
language,
}).then(session => {
store.setItem(SESSION_VAR, JSON.stringify(session));
});
console.log(session);
window.localStorage.setItem('umami.session', JSON.stringify(session));
}

await post(`${process.env.UMAMI_URL}/api/collect`, {
post(`${HOST_URL}/api/collect`, {
type: 'pageview',
payload: { url, referrer, session: JSON.parse(window.localStorage.getItem('umami.session')) },
payload: { url, referrer, session: JSON.parse(store.getItem(SESSION_VAR)) },
}).then(response => {
if (!response.status) {
store.removeItem(SESSION_VAR);
}
});
}
})();
}
Loading

0 comments on commit 11f1afe

Please sign in to comment.