Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FRESH PR] add: visitor-counter-api #303

Merged
merged 2 commits into from
Jul 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions New_APIs/visitor-counter-api/.env_sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
REDIS_HOST=your-redis-host
REDIS_PORT=your-redis-port
REDIS_PASSWORD=your-redis-password
5 changes: 5 additions & 0 deletions New_APIs/visitor-counter-api/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules/
vscode/
.env
# Local Netlify folder
.netlify
11 changes: 11 additions & 0 deletions New_APIs/visitor-counter-api/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Released under MIT License

Copyright (c) 2013 Mark Otto.

Copyright (c) 2017 Andrew Fong.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
133 changes: 133 additions & 0 deletions New_APIs/visitor-counter-api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Visitor Counter API

This project is a serverless API hosted on Netlify using Redis Cloud as the database. The API allows for managing a simple counter that can be incremented, reset, or retrieved. It supports CORS for cross-origin requests.

## Table of Contents
- [Getting Started](#getting-started)
- [API Endpoints](#api-endpoints)
- [GET /](#get-)
- [OPTIONS /](#options-)
- [Environment Variables](#environment-variables)
- [Dependencies](#dependencies)
- [Error Handling](#error-handling)
- [Development](#development)
- [Deployment](#deployment)
- [License](#license)

## Getting Started

### Prerequisites

- [Node.js](https://nodejs.org/)
- [Redis Cloud Account](https://redis.com/redis-enterprise-cloud/overview/)
- [Netlify Account](https://www.netlify.com/)

### Installation

1. Clone the repository:
```sh
git clone https://github.com/mondalsurojit/Visitor-Counter-API.git
```

2. Install dependencies:
```sh
npm install
```

3. Set up environment variables (create a `.env` file):
```env
REDIS_HOST=your-redis-host
REDIS_PORT=your-redis-port
REDIS_PASSWORD=your-redis-password
```

4. Deploy to Netlify by linking your repository and configuring environment variables through the Netlify dashboard.

## API Endpoints

### GET /

This endpoint increments the counter by 1 if no query parameters are provided. If the `q` parameter is set to `reset`, it resets the counter to 0. If the `q` parameter is set to any other value, it returns the current count without incrementing.

#### Request

- Method: `GET`
- URL: `https://visitor-counter-api.netlify.app/.netlify/functions/counter/`

#### Query Parameters

| Parameter | Type | Description |
|-----------|--------|-------------------------------------------------|
| q | string | Optional. If `reset`, the counter is reset to 0.|

#### Response

- Status: `200 OK`
- Body: JSON object containing the current count value

```json
{
"value": <current_count>
}
```

### OPTIONS /

This endpoint handles CORS preflight requests.

#### Request

- Method: `OPTIONS`
- URL: `https://visitor-counter-api.netlify.app/.netlify/functions/counter/`

#### Response

- Status: `200 OK`
- Body: `"Preflight OK"`

## Environment Variables

| Variable | Description |
|------------------|------------------------------------------|
| `REDIS_HOST` | The hostname of your Redis instance. |
| `REDIS_PORT` | The port number of your Redis instance. |
| `REDIS_PASSWORD` | The password for your Redis instance. |

## Dependencies

- [redis](https://www.npmjs.com/package/redis): Redis client for Node.js.
- [dotenv](https://www.npmjs.com/package/dotenv): Module to load environment variables from a .env file.
- [netlify-cli](https://www.npmjs.com/package/netlify-cli): Command line tool for Netlify.
- [netlify-lambda](https://www.npmjs.com/package/netlify-lambda): Tools for building and deploying serverless functions with Netlify.
- [serverless-http](https://www.npmjs.com/package/serverless-http): Serverless framework for running Node.js HTTP servers.


## Error Handling

In case of an error while interacting with Redis, the API responds with:

- Status: `500 Internal Server Error`
- Body: `"Error interacting with Redis"`

## Development

To run the project locally, follow these steps:

1. Ensure Redis Cloud is configured and accessible.
2. Ensure the `.env` file is correctly set up with Redis credentials.
3. Run the serverless function locally using Netlify CLI:
```sh
netlify dev
```

## Deployment

Deploy the API using Netlify by following their [serverless function deployment guide](https://docs.netlify.com/functions/overview/).

## License

This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

---

Feel free to modify this documentation to better suit your specific requirements and project structure.
24 changes: 24 additions & 0 deletions New_APIs/visitor-counter-api/deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

118 changes: 118 additions & 0 deletions New_APIs/visitor-counter-api/functions/counter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
const { createClient } = require('redis');

const client = createClient({
password: process.env.REDIS_PASSWORD,
socket: {
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT
}
});

let connected = false;

const connectToRedis = async () => {
if (!connected) {
await client.connect();
connected = true;
}
};

exports.handler = async (event, context) => {
const { httpMethod, queryStringParameters } = event;

// CORS headers
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
};

if (httpMethod === 'OPTIONS') {
// Respond to preflight CORS requests
return {
statusCode: 200,
headers,
body: 'Preflight OK',
};
}

await connectToRedis();

if (httpMethod === 'GET') {
if (!queryStringParameters || !queryStringParameters.q || queryStringParameters.q === '') {
// Read the current count from Redis
try {
let currentCount = await client.get('count');
if (currentCount === null) {
currentCount = 0;
} else {
currentCount = parseInt(currentCount, 10);
}

currentCount += 1;

// Write the new count back to Redis
await client.set('count', currentCount.toString());

return {
statusCode: 200,
headers,
body: JSON.stringify({ value: currentCount }),
};
} catch (err) {
console.error('Error interacting with Redis:', err);
return {
statusCode: 500,
headers,
body: 'Error interacting with Redis',
};
}
} else if (queryStringParameters.q === 'reset') {
// Reset the count
try {
await client.set('count', '0');
return {
statusCode: 200,
headers,
body: JSON.stringify({ value: 0 }),
};
} catch (err) {
console.error('Error interacting with Redis:', err);
return {
statusCode: 500,
headers,
body: 'Error interacting with Redis',
};
}
} else {
// Return current count
try {
let currentCount = await client.get('count');
if (currentCount === null) {
currentCount = 0;
} else {
currentCount = parseInt(currentCount, 10);
}

return {
statusCode: 200,
headers,
body: JSON.stringify({ value: currentCount }),
};
} catch (err) {
console.error('Error interacting with Redis:', err);
return {
statusCode: 500,
headers,
body: 'Error interacting with Redis',
};
}
}
} else {
return {
statusCode: 405,
headers,
body: 'Method Not Allowed',
};
}
};
3 changes: 3 additions & 0 deletions New_APIs/visitor-counter-api/netlify.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[build]
functions = "/functions"
included_files = ["/count.txt"]
Loading
Loading