Skip to content

Instantly share code, notes, and snippets.

@chrislaughlin
Last active October 27, 2020 21:29
Show Gist options
  • Save chrislaughlin/3ec3d195326d99b4d053a15e27f7170a to your computer and use it in GitHub Desktop.
Save chrislaughlin/3ec3d195326d99b4d053a15e27f7170a to your computer and use it in GitHub Desktop.
Hit Counter
const faunadb = require('faunadb');

exports.handler = async (event) => {
    const q = faunadb.query;
    const client = new faunadb.Client({
        secret: 'fnAD5MhMdOACB7iOmssIe7HfmYc9m_2ZdSF7PsOA',
    });

    // const { site } = event.queryStringParameters;
    // if (!site) {
    //     return {
    //         statusCode: 400,
    //         body: JSON.stringify({
    //             message: 'Site not provided',
    //         }),
    //     };
    // }
    const site = 'test'
    // Check and see if the doc exists.

    const doesDocExist = await client.query(
        q.Exists(q.Match(q.Index('hits_for_site'), site))
    );
    console.log('check count for site exists:  ', doesDocExist);

    if (!doesDocExist) {
        console.log(`Set count' for '${site}' to zero`);
        await client.query(
            q.Create(q.Collection('hits'), {
                data: {site, count: 0},
            })
        );
    }

    // Fetch the document for-real
    const document = await client.query(
        q.Get(q.Match(q.Index('hits_for_site'), site))
    );
    console.log(document);
    console.log('updating count by 1');
    await client.query(
        q.Update(document.ref, {
            data: {
                count: document.data.count + 1,
            },
        })
    );
    console.log(`returning site count: ${document.data.count}`);
    return {
        statusCode: 200,
        body: JSON.stringify({
            count: document.data.count,
        }),
    };
};
const URL = JSON.parse(event.body).url;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment