Skip to content

Commit

Permalink
adjustments to return type, styles, etc
Browse files Browse the repository at this point in the history
  • Loading branch information
jmonster committed Mar 9, 2023
1 parent 8143741 commit 83e137e
Show file tree
Hide file tree
Showing 10 changed files with 74 additions and 38 deletions.
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.

2 changes: 1 addition & 1 deletion 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 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
21 changes: 21 additions & 0 deletions src/react-ezql/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,18 @@ 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) => {
Expand Down Expand Up @@ -93,3 +100,17 @@ Each HTML Element has been an assigned a meaningful classname that you can style
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
```
8 changes: 4 additions & 4 deletions src/react-ezql/package-lock.json

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

2 changes: 1 addition & 1 deletion src/react-ezql/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
"c8": "^7.13.0",
"eslint": "^8.35.0",
"eslint-plugin-react": "^7.32.2",
"ezql": "^0.0.3",
"ezql": "^0.0.4",
"jsdom": "^21.1.0",
"postcss": "^8.4.21",
"react": "^18.2.0",
Expand Down
5 changes: 2 additions & 3 deletions src/react-ezql/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,10 @@ function App() {
token={token}
setShouldDisplayEzql={setShouldDisplayEzql}
suggestions={suggestions}
didSubmitWithValue={(value) => {
console.log(`query: ${value}`)
didSubmitWithValue={(_value) => {
setShouldDisplayEzql(false)
}}
onResults={(json) => console.dir(json)}
onResults={(sql) => console.log(sql)}
className="optional-for-styling-convenience"
/>
)}
Expand Down
42 changes: 24 additions & 18 deletions src/react-ezql/src/components/ezql-prompt.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,47 @@ import { useCallback, useRef, useState } from 'react'
import Modal from './modal'
import { SuggestSearchListItem } from './suggest-search-list-item'
import { classNames } from '../lib/class-names'
import {EZQL, Prompt} from 'ezql'
import { EZQL, Prompt } from 'ezql'

import styles from './ezql-prompt.module.css'

export type EzqlPromptOpts = {
token: string
setShouldDisplayEzql: (value: boolean) => void
onResults: (data: object) => void
onResults: (data: string | Object) => void
didSubmitWithValue?: (query: string) => void
suggestions?: Array<string>
className?: string
}

export default function EzqlPrompt({
token,
setShouldDisplayEzql,
didSubmitWithValue,
onResults,
suggestions,
className,
token, // authenticates and identifies the scope of this request with Outerbase
setShouldDisplayEzql, // toggles display of the modal
didSubmitWithValue, // fires before the request goes to Outerbase
onResults, // fires upon receiving a response from Outerbase
suggestions, // pre-populate the list of suggested queries
className, // optional styling classes
}: EzqlPromptOpts) {
const [query, setQuery] = useState('')

const listRef = useRef<HTMLUListElement>(null)

const onSubmission = useCallback(async (phrase: string) => {
if (!token) throw new Error("Missing token")
if (didSubmitWithValue) didSubmitWithValue(phrase)
const onSubmission = useCallback(
async (phrase: string) => {
if (!token) throw new Error('Missing token')
if (didSubmitWithValue) didSubmitWithValue(phrase)

// TODO make request to Outerbase
const ezql = new EZQL({ token })
const result = await ezql.prompt(phrase, Prompt.sql)
console.dir(result)
// and pass the result to onResults()
}, [token])
const ezql = new EZQL({ token, host: 'app.dev.outerbase.com' })
const {
response: {
query: { text: sql },
},
} = await ezql.prompt(phrase, Prompt.sql)

onResults(sql)
},
[token]
)

return (
<Modal didDismiss={() => setShouldDisplayEzql(false)} className={classNames('ezql-prompt-modal', className)}>
Expand Down
1 change: 0 additions & 1 deletion src/react-ezql/vite.config.web.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
Expand Down

0 comments on commit 83e137e

Please sign in to comment.