Skip to content

Commit

Permalink
#35 Refactor repo for consistency (#45)
Browse files Browse the repository at this point in the history
  • Loading branch information
RishabhC-137 authored Oct 5, 2024
1 parent e4e405d commit 18fe135
Show file tree
Hide file tree
Showing 12 changed files with 87 additions and 54 deletions.
File renamed without changes.
71 changes: 52 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,31 @@
# DiceDB Playground Web

DiceDB Playground is an interactive platform designed to let users experiment with [DiceDB](https://github.com/dicedb/dice/) commands in a live environment, similar to the Go Playground.
Allows users to search and play with various DiceDB commands in real-time.
DiceDB Playground is an interactive platform designed to let users experiment with [DiceDB](https://github.com/dicedb/dice/) commands in a live environment, similar to the Go Playground. It allows users to search and play with various DiceDB commands in real-time.

This repository hosts frontend service implementation of the Playground.
This repository hosts the frontend service implementation of the Playground.

## Setup Using Docker

```
To start the playground using Docker, run:

```bash
docker-compose up
```

## Prerequisites

Ensure you have the following installed:

- **Node.js** (v16.x or later)
- **Node.js** (v16.13.0 or later)
- **Yarn** (or npm)
- **Next.js** (v13.x or later)
- **Next.js** (v14.2.13 or later)

To ensure you're using the correct Node.js version, you can check or set up the required version using NVM:

```bash
nvm install 16.13.0
nvm use 16.13.0
```

## Installation

Expand All @@ -39,11 +47,11 @@ npm run dev

This will launch the app on [http://localhost:3000](http://localhost:3000). The app will automatically reload if you make changes to the code.

If you want to bring up backend and DiceDB for local end to end development, follow below steps:
### Setting Up Backend and DiceDB for Local Development

1. Update `docker-compose.yml` file with below code:
1. Update `docker-compose.yml` file with the following code:

```yml
```yaml
version: "3.8"

services:
Expand All @@ -64,21 +72,43 @@ services:
- DICE_ADDR=dicedb:7379
```
2. Run below command to start backend server and DiceDB
2. Run the following command to start the backend server and DiceDB:
```shell
```bash
docker-compose up
```

## Step-by-Step Setup for End-to-End Development with Docker
We have added `Dockerfile.dev` which is for development purposes, ensuring your Next.js application supports hot reloading and reflects code changes without requiring image rebuilds.

We have added `Dockerfile.dev`, which is for development purposes, ensuring your Next.js application supports hot reloading and reflects code changes without requiring image rebuilds.

`docker-compose.dev.yml` configures Docker Compose to build and run your Next.js app in development mode.

```shell
To build and run the development mode:

```bash
docker-compose -f docker-compose.dev.yml up --build
```

## Prettier Scripts

To ensure consistent code formatting, we use Prettier. It runs automatically as part of the GitHub workflow, but in case of a workflow failure, you can run Prettier manually.

### Running Prettier Locally

To run Prettier and fix formatting issues locally:

```bash
npm run prettier:format
```

This command will format all `.js`, `.jsx`, `.ts`, `.tsx`, `.json`, and `.css` files.

To check for any formatting issues without fixing them:

```bash
npm run prettier:check
```

## Building for Production

Expand All @@ -94,19 +124,22 @@ After the build is complete, you can start the production server with:
npm run start
```

## Running the test cases
## Running the Test Cases

To run the test cases, execute the following command:

To run the test cases, execute following command:
```bash
npm run test
```

To execute the test cases simultaneously as you make changes to the files, execute following command:
To execute the test cases simultaneously as you make changes to the files, execute the following command:

```bash
npm run test:watch
```

To get the test coverage of the project, execute following command:
To get the test coverage of the project, execute the following command:

```bash
npm run test:coverage
```
Expand All @@ -120,8 +153,8 @@ The main components of the DiceDB Playground include:

Feel free to extend or modify the components to suit your needs.

## How to contribute
## How to Contribute

The Code Contribution Guidelines are published at [CONTRIBUTING.md](CONTRIBUTING.md); please read them before you start making any changes. This would allow us to have a consistent standard of coding practices and developer experience.
The Code Contribution Guidelines are published at [CONTRIBUTING.md](CONTRIBUTING.md); please read them before you start making any changes. This will ensure a consistent standard of coding practices and developer experience.

Contributors can join the [Discord Server](https://discord.gg/6r8uXWtXh7) for quick collaboration.
2 changes: 1 addition & 1 deletion docker-compose.dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ services:
backend:
build:
context: .
dockerfile: Dockerfile_Backend
dockerfile: PlaygroundMonoDockerfile
ports:
- "8080:8080"
depends_on:
Expand Down
11 changes: 5 additions & 6 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
version: '3.8'

services:
dicedb:
Expand All @@ -9,20 +8,20 @@ services:
backend:
build:
context: .
dockerfile: Dockerfile_Backend
dockerfile: PlaygroundMonoDockerfile
ports:
- "8080:8080"
depends_on:
- dicedb
- dicedb
environment:
- DICE_ADDR=dicedb:7379

frontend:
build:
context: .
dockerfile: Dockerfile
dockerfile: Dockerfile.dev # Specify the correct Dockerfile for the frontend
ports:
- "3000:3000"
depends_on:
- dicedb
- backend
- dicedb
- backend
2 changes: 1 addition & 1 deletion src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// components
import Playground from '@/components/Playground/Playground';
import Footer from '@/components/Footer/Footer'; // comment this to hide footer
import Footer from '@/components/Footer/Footer';

export default function Home() {
return (
Expand Down
4 changes: 2 additions & 2 deletions src/components/Playground/Playground.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use client';

// Components
import Cli from '@/components/CLI/CLI';
import Shell from '@/components/Shell/Shell';
import SearchBox from '@/components/Search/SearchBox';
import { Dice1, Dice3, Dice5, Info } from 'lucide-react';

Expand Down Expand Up @@ -43,7 +43,7 @@ export default function Playground() {
</div>
</div>
<div className="h-64 md:h-[30rem] bg-gray-100 rounded-lg overflow-hidden shadow-md">
<Cli decreaseCommandsLeft={decreaseCommandsLeft} />
<Shell decreaseCommandsLeft={decreaseCommandsLeft} />
</div>
</div>

Expand Down
12 changes: 6 additions & 6 deletions src/components/CLI/CLI.tsx → src/components/Shell/Shell.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
// src/components/CLI/CLI.tsx
// src/components/Shell/Shell.tsx
'use client';

// hooks
import { useCli } from './hooks/useCli';
import { useShell } from './hooks/useShell';

interface CliProps {
interface ShellProps {
decreaseCommandsLeft: () => void;
}

export default function Cli({ decreaseCommandsLeft }: CliProps) {
export default function Shell({ decreaseCommandsLeft }: ShellProps) {
const {
handleInputChange,
handleKeyDown,
terminalRef,
inputRef,
output,
command,
} = useCli(decreaseCommandsLeft);
} = useShell(decreaseCommandsLeft);
return (
<div
ref={terminalRef}
Expand All @@ -42,7 +42,7 @@ export default function Cli({ decreaseCommandsLeft }: CliProps) {
value={command}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
data-testid="cli-input"
data-testid="shell-input"
className="w-full bg-transparent outline-none text-white"
/>
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import CLI from '../CLI';
import Shell from '../Shell';

const decreaseCommandsLeftMock = jest.fn();

Expand All @@ -16,10 +16,12 @@ const dummyCommands = [

const setupTest = () => {
const user = userEvent.setup();
const utils = render(<CLI decreaseCommandsLeft={decreaseCommandsLeftMock} />);
const utils = render(
<Shell decreaseCommandsLeft={decreaseCommandsLeftMock} />,
);

const terminalElement = screen.getByTestId('terminal');
const cliInputElement = screen.getByTestId<HTMLInputElement>('cli-input');
const cliInputElement = screen.getByTestId<HTMLInputElement>('shell-input');

const typeMultipleCommands = async () => {
for (const command of dummyCommands) {
Expand All @@ -36,7 +38,7 @@ const setupTest = () => {
};
};

describe('CLI Component', () => {
describe('Shell Component', () => {
it('should focus on terminal element click', async () => {
const { terminalElement, cliInputElement, user } = setupTest();
await user.click(terminalElement);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
import { useState, useEffect, useRef, KeyboardEvent, ChangeEvent } from 'react';

// utils
import { handleCommand } from '@/shared/utils/cliUtils';
import blacklistedCommands from '@/shared/utils/blacklist'; // Assuming you added blacklist here
import { handleCommand } from '@/shared/utils/shellUtils';
import blacklistedCommands from '@/shared/utils/blacklist';

export const useCli = (decreaseCommandsLeft: () => void) => {
export const useShell = (decreaseCommandsLeft: () => void) => {
// states
const [command, setCommand] = useState('');
const [output, setOutput] = useState<string[]>([]);
const [tempCommand, setTempCommand] = useState('');
//Initialise the command history with sessionStorage
// Initialise the command history with sessionStorage
const [commandHistory, setCommandHistory] = useState<string[]>([]);
const [historyIndex, setHistoryIndex] = useState<number>(-1);

Expand Down Expand Up @@ -40,7 +40,7 @@ export const useCli = (decreaseCommandsLeft: () => void) => {
}
}, [output]);

//Load initial command history if present
// Load initial command history if present
useEffect(() => {
const savedHistory = sessionStorage.getItem('terminalHistory');
const commandHistory = savedHistory ? JSON.parse(savedHistory) : [];
Expand Down
7 changes: 3 additions & 4 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
// src/lib/api.ts
import { CLI_COMMAND_URL } from '@/shared/constants/apiEndpoints';
import { SHELL_COMMAND_URL } from '@/shared/constants/apiEndpoints';

export const executeCLICommandOnServer = async (
export const executeShellCommandOnServer = async (
cmd: string,
cmdOptions: object,
): Promise<string> => {
try {
const response = await fetch(`${CLI_COMMAND_URL}/${cmd}`, {
const response = await fetch(`${SHELL_COMMAND_URL}/${cmd}`, {
method: 'POST',
body: JSON.stringify(cmdOptions),
headers: {
'Content-Type': 'application/json',
},
});

// TODO: This needs to be looked at
const data = await response.json();
if (Object.prototype.hasOwnProperty.call(data, 'data')) {
return data.data;
Expand Down
2 changes: 1 addition & 1 deletion src/shared/constants/apiEndpoints.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
// This folder will contain or hold constants. For example in this particular file we can store the api endpoints as constants
export const CLI_COMMAND_URL = 'http://localhost:8080/shell/exec';
export const SHELL_COMMAND_URL = 'http://localhost:8080/shell/exec';
10 changes: 5 additions & 5 deletions src/shared/utils/cliUtils.ts → src/shared/utils/shellUtils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// src/shared/utils/cliUtils.ts
// src/shared/utils/shellUtils.ts

import { executeCLICommandOnServer } from '@/lib/api';
import { executeShellCommandOnServer } from '@/lib/api';
import { CommandHandler } from '@/types';

export const handleCommand = async ({ command, setOutput }: CommandHandler) => {
Expand All @@ -20,7 +20,7 @@ export const handleCommand = async ({ command, setOutput }: CommandHandler) => {
try {
const [key] = args;
const cmdOptions = { key: key };
result = await executeCLICommandOnServer(cmd, cmdOptions);
result = await executeShellCommandOnServer(cmd, cmdOptions);
setOutput((prevOutput) => [...prevOutput, newOutput, result]);
} catch (error: unknown) {
console.error('Error executing command:', error);
Expand All @@ -34,7 +34,7 @@ export const handleCommand = async ({ command, setOutput }: CommandHandler) => {
const [key, value] = args;
try {
const cmdOptions = { key: key, value: value };
result = await executeCLICommandOnServer(cmd, cmdOptions);
result = await executeShellCommandOnServer(cmd, cmdOptions);
setOutput((prevOutput) => [...prevOutput, newOutput, result]);
} catch (error: unknown) {
console.error('Error executing command:', error);
Expand All @@ -53,7 +53,7 @@ export const handleCommand = async ({ command, setOutput }: CommandHandler) => {
const [keys] = args;
try {
const cmdOptions = { keys: [keys] };
result = await executeCLICommandOnServer(cmd, cmdOptions);
result = await executeShellCommandOnServer(cmd, cmdOptions);
setOutput((prevOutput) => [...prevOutput, newOutput, result]);
} catch (error: unknown) {
console.error('Error executing command:', error);
Expand Down

0 comments on commit 18fe135

Please sign in to comment.