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;