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

<EzqlPrompt /> #24

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
Draft
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
18 changes: 13 additions & 5 deletions .github/workflows/static.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,24 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Set up Node
uses: actions/setup-node@v3
with:
node-version: 18
cache: 'npm'
- name: Install dependencies
working-directory: ./src/react-ezql
run: npm install
- name: Build
working-directory: ./src/react-ezql
run: npm run build:web
- name: Setup Pages
uses: actions/configure-pages@v3
- name: Install rollup.js
run: npm install rollup@3
- name: Copy bundled EZQL to web directory
run: npm run update:demo
- name: Upload artifact
uses: actions/upload-pages-artifact@v1
with:
path: './demo/web'
# Upload dist repository
path: './src/react-ezql/dist/page'
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v1
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Project
dist
src/react-ezql/dist
demo/web/bundle.*

# Logs
Expand Down
14 changes: 8 additions & 6 deletions __tests__/lib/ezql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,7 @@ describe('register EZQL', () => {
test('prompt.data yields data', async () => {
expect.assertions(2)

const mockedResponse = '42'
fetch.mockResolvedValue(new Response(mockedResponse))
fetch.mockResolvedValue(new Response('42'))

const query = 'What is the answer to life, the univerise and everything?'
const response = await ob.prompt(query, Prompt.data)
Expand All @@ -92,23 +91,26 @@ describe('register EZQL', () => {
body: JSON.stringify({ query, run: true }),
method: 'POST',
})
expect(response).toEqual(mockedResponse)
expect(response).toEqual(42)
})

test('prompt.sql yields SQL', async () => {
expect.assertions(2)

const mockedResponse = 'SELECT answer FROM ultimate_question;'
const serverResponse = {"response": {"query": {"text": "SELECT answer FROM ultimate_question;"}}, "success": true}
const mockedResponse = JSON.stringify(serverResponse)

fetch.mockResolvedValue(new Response(mockedResponse))

const query = 'What is the answer to life, the univerise and everything?'
const response = await ob.prompt(query, Prompt.sql)
const clientResponse = await ob.prompt(query, Prompt.sql)

expect(fetch).toHaveBeenCalledWith(`https://${DEFAULT_HOST}/api/v1/ezql`, {
headers: { 'Content-Type': 'application/json', 'x-source-token': token },
body: JSON.stringify({ query, run: false }),
method: 'POST',
})
expect(response).toEqual(mockedResponse)

expect(clientResponse).toEqual(serverResponse)
})
})
4 changes: 2 additions & 2 deletions package-lock.json

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

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ezql",
"version": "0.0.3",
"version": "0.0.4",
"description": "Ask your database questions, anywhere.",
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
Expand All @@ -26,7 +26,7 @@
"build:umd": "rollup --config config/rollup.config.js --bundleConfigAsCjs",
"update:demo": "npm run build:umd && node demo/copy-assets.mjs",
"prepare": "husky install",
"prepack": "npm run build"
"prepack": "rm -rf ./dist && npm run build"
},
"repository": {
"type": "git",
Expand Down
13 changes: 11 additions & 2 deletions src/lib/ezql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@ export type EZQLOpts = {
host?: string
}

type EZQLResponse = {
success: boolean
response: {
query: {
text: string
}
}
}

export enum Prompt {
sql = 'sql',
data = 'data',
Expand Down Expand Up @@ -42,7 +51,7 @@ export class EZQL {
}
}

async prompt(phrase: string, type: Prompt): Promise<string> {
async prompt(phrase: string, type: Prompt): Promise<EZQLResponse> {
// console.debug(`prompt("${phrase}", ${type})`)
if (!phrase || !type) throw new Error(`EZQL.prompt requires a 'phrase' and 'type' parameter`)
if (!Object.values(Prompt).includes(type))
Expand All @@ -60,7 +69,7 @@ export class EZQL {
}),
})

if (result.status === 200) return result.text()
if (result.status === 200) return result.json()
else {
throw new Error(`${result.status}: ${result.statusText}`)
}
Expand Down
116 changes: 116 additions & 0 deletions src/react-ezql/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
## Installation

```sh
npm install --save-dev react-ezql
```

## Usage

**Minimal usage**
- `token` is provided from the Outerbase dashboard
- `suggestions` - a list of queries that can be chosen from a list
- `setShouldDisplayEzql` is a setter for toggling whether the modal is displayed; provide a setter that when true will remove the modal from your page
- `didSubmitWithValue` is called when a query has been submitted to the modal _before_ a request has been made to Outerbase
- `onResults` is called with the resulting SQL string or JSON data (depending on the Prompt type specified)
- `className` provides optional styling classes to be added to the modal

```tsx
import EzqlPrompt from 'react-ezql'

<EzqlPrompt
token={'arbitrary-value-asdf-1234'}
setShouldDisplayEzql={setShouldDisplayEzql}
suggestions={['How many books sold last week', 'How many new users signed up today']}
didSubmitWithValue={(value) => {
console.log(`query: ${value}`)
setShouldDisplayEzql(false)
}}
onResults={(json) => console.dir(json)}
className="optional-for-styling-convenience"
/>
```

**Example App.tsx**
Here lies a demonstration conditionally showing/hiding the prompt

```tsx
import './App.css'
import EzqlPrompt from 'react-ezql'
import { useEffect, useState } from 'react'

const TRIGGERS = ['KeyK', 'Slash']

function App() {
const [shouldDisplayEzql, setShouldDisplayEzql] = useState(false)
const suggestions = ['How many books sold last week', 'How many new users signed up today']

// listen for the trigger to display the modal
useEffect(() => {
function ezqlTriggerListener(ev: KeyboardEvent) {
if (TRIGGERS.includes(ev.code) && ev.getModifierState('Meta')) {
setShouldDisplayEzql(true)
}
}

// BEGIN listening for the trigger(s)
document.addEventListener('keydown', ezqlTriggerListener)

return () => {
// STOP listening for the trigger(s)
document.removeEventListener('keydown', ezqlTriggerListener)
}
}, [])

return (
<>
{shouldDisplayEzql && (
<EzqlPrompt
setShouldDisplayEzql={setShouldDisplayEzql}
suggestions={suggestions}
didSubmitWithValue={(value) => {
console.log(`query: ${value}`)
setShouldDisplayEzql(false)
}}
onResults={(json) => console.dir(json)}
className="optional-for-styling-convenience"
/>
)}
</>
)
}

export default App
```

## Styling

<!-- TODO? Perhaps we make it possible to utilize CSS variables (when defined) -->

Each HTML Element has been an assigned a meaningful classname that you can style in your own CSS

- Use the web inspector to reveal which class names are assigned to which elements
- You may optionally pass `className` to the component, i.e. `<EzqlPrompt className="arbitrary-value">`. This allows more precise scoping of CSS:

```css
.arbitrary-value.ezql-prompt-modal {
background-color: black;
}
,
.arbitrary-value .input-container {
color: white;
}
```

## Local development of react-ezql
pnpm is recommended as `npm link` does not work properly (as of 03/09/2023) with regards to `npm link`ing `lib/ezql` to `react-ezql`. Instead, do this from the `react-ezql` directory:

```sh
pnpm install
pnpm link ../../
```

And be sure to have also built your latest changes in `lib/ezql`, i.e.:

```sh
npm run build
```
13 changes: 13 additions & 0 deletions src/react-ezql/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
Loading