feat: launch

This commit is contained in:
Reinaldy Rafli 2021-07-11 18:04:04 +07:00
commit 5f78a34305
11 changed files with 1916 additions and 0 deletions

20
.eslintrc.js Normal file
View File

@ -0,0 +1,20 @@
module.exports = {
env: {
browser: true,
es2021: true,
node: true,
},
extends: [
'xo-space',
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'@typescript-eslint',
],
rules: {
},
};

36
.github/workflows/coverage.yml vendored Normal file
View File

@ -0,0 +1,36 @@
name: Code Coverage
on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
jobs:
coverage:
name: Codecov
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: 14
- name: Installing dependencies
run: yarn install
- name: Lint
run: yarn run lint
- name: Running test
run: yarn run test
- name: Upload to Codecov
uses: codecov/codecov-action@v1
with:
token: ${{ secrets.CODECOV_TOKEN }}

125
.gitignore vendored Normal file
View File

@ -0,0 +1,125 @@
# Created by https://www.toptal.com/developers/gitignore/api/node
# Edit at https://www.toptal.com/developers/gitignore?templates=node
### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
.env.production
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
# End of https://www.toptal.com/developers/gitignore/api/node

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-present Reinaldy Rafli
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.

59
README.md Normal file
View File

@ -0,0 +1,59 @@
# SQL DSN for your Node App
Based on an idea from [@ronnygunawan](https://github.com/ronnygunawan). This was supposed to be a challenge for someone else, but I thought, why not? Lol.
As always:
* Supports CJS and ESM
* Built-in typings
* No external dependencies
```bash
npm install sql-dsn
```
## What this does?
This outputs simple SQL query & argument object from your template literal string.
```js
import { sql } from 'sql-dsn'
const query = sql`INSERT INTO users (name, email, age) VALUES (${`Thomas Worgdjik`}, ${`thom@thunder.zn`}, ${30})`
// {
// sql: 'INSERT INTO users (name, email, age) VALUES ($1, $2, $3)',
// values: ['Thomas Worgdjik', 'thom@thunder.zn', 30]
// }
// Oh, you work with MySQL instead of Postgres? Sure!
const postgres = query.formatQuestion()
// {
// sql: 'INSERT INTO users (name, email, age) VALUES (?, ?, ?)',
// values: ['Thomas Worgdjik', 'thom@thunder.zn', 30]
// }
// More elegant way to do that is this:
const query = sql`INSERT INTO users (name, email, age) VALUES (${`Thomas Worgdjik`}, ${`thom@thunder.zn`}, ${30})`.formatQuestion()
// Your database work with colon notation? Something like :1 :2 etc? No problem.
const colon = query.formatColon()
// {
// sql: 'INSERT INTO users (name, email, age) VALUES (:1, :2, :3)',
// values: ['Thomas Worgdjik', 'thom@thunder.zn', 30]
// }
// Your database work with @p notation? Yeah, we can do that.
const atp = query.formatAtP()
// {
// sql: 'INSERT INTO users (name, email, age) VALUES (@p1, @p2, @p3)',
// values: ['Thomas Worgdjik', 'thom@thunder.zn', 30]
// }
```
Want more features? Open something up on [issues](https://github.com/aldy505/sql-dsn).

58
package.json Normal file
View File

@ -0,0 +1,58 @@
{
"name": "sql-dsn",
"version": "0.0.1",
"description": "SQL as template literal",
"author": "Reinaldy Rafli <aldy505@tutanota.com>",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/aldy505/sql-dsn.git"
},
"bugs": {
"url": "https://github.com/aldy505/sql-dsn/issues"
},
"homepage": "https://github.com/aldy505/sql-dsn#readme",
"main": "dist/index.cjs",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"./package.json": "./package.json",
"./*": "./*"
},
"files": [
"dist",
"README.md",
"LICENSE"
],
"directories": {
"lib": "./src",
"test": "./test"
},
"scripts": {
"build": "rollup -c",
"lint": "eslint --ext .js,.ts --ignore-path .gitignore .",
"lint:fix": "eslint --fix --ext .js,.ts --ignore-path .gitignore .",
"coverage": "c8 --reporter=text --reporter=lcov yarn run uvu",
"uvu": "uvu -r esbuild-register test",
"tdd": "yarn -s uvu; watchlist src/ -- yarn -s uvu",
"test": "yarn run coverage"
},
"devDependencies": {
"@types/node": "^16.3.1",
"@typescript-eslint/eslint-plugin": "^4.28.2",
"@typescript-eslint/parser": "^4.28.2",
"c8": "^7.7.3",
"esbuild-register": "^2.6.0",
"eslint": "^7.30.0",
"eslint-config-xo-space": "^0.28.0",
"rollup": "^2.53.1",
"rollup-plugin-typescript2": "^0.30.0",
"typescript": "^4.3.5",
"uvu": "^0.5.1",
"watchlist": "^0.2.3"
}
}

19
rollup.config.js Normal file
View File

@ -0,0 +1,19 @@
import ts from 'rollup-plugin-typescript2';
export default {
input: 'src/index.ts',
output: [
{
file: 'dist/index.cjs',
format: 'cjs',
},
{
file: 'dist/index.js',
format: 'esm',
},
],
external: ['crypto', 'fs', 'path'],
plugins: [
ts(),
],
};

56
src/index.ts Normal file
View File

@ -0,0 +1,56 @@
export interface SqlObject {
sql: string
values: TemplateStringsArray
formatQuestion?: () => SqlObject
formatColon?: () => SqlObject
formatAtP?: () => SqlObject
}
/**
* Simple template literal to create a SQL query object
* @returns {SqlObject} An object of your SQL and arguments
* @example
* const query = sql`select * from users where email = ${`something@mail.com`}`
* // query.sql = 'select * from users where email = $1'
* // query.values = ['something@mail.com']
*
* // Convert to MySQL question mark notation:
* const mysql = query.formatQuestion()
* // mysql.sql = 'select * from users where email = ?'
*
* // Convert to colon notation:
* const colon = query.formatColon()
* // colon.sql = 'select * from users where email = :1'
*/
export function sql(string: string[], ...params: TemplateStringsArray): SqlObject {
const sql = string.map((v, i) => (string.length - 1 === i) ? v : `${v}$${i + 1}`).join('');
function formatQuestion(): SqlObject {
return {
sql: sql.replace(/\$[0-Infinity]/gi, '?'),
values: params,
};
}
function formatColon(): SqlObject {
return {
sql: sql.replace(/\$/gi, ':'),
values: params,
};
}
function formatAtP(): SqlObject {
return {
sql: sql.replace(/\$/gi, '@p'),
values: params,
};
}
return {
sql,
values: params,
formatQuestion,
formatColon,
formatAtP,
};
}

32
test/index.ts Normal file
View File

@ -0,0 +1,32 @@
import {test} from 'uvu';
import * as assert from 'uvu/assert';
import {sql} from '../src/index';
test('should be able to parse select query', () => {
const query = sql`select * from 'users' where email = ${'example@mail.com'}`;
assert.equal(query.sql, 'select * from \'users\' where email = $1');
assert.equal(query.values, ['example@mail.com']);
});
test('should be able to parse insert query', () => {
const query = sql`insert into users (name, age, profession) values (${'Jonas'}, ${21}, ${'pengangguran'})`;
assert.equal(query.sql, 'insert into users (name, age, profession) values ($1, $2, $3)');
assert.equal(query.values, ['Jonas', 21, 'pengangguran']);
});
test('should be able to parse to question marks', () => {
const query = sql`select * from 'users' where email = ${'example@mail.com'}`.formatQuestion();
assert.equal(query, {sql: 'select * from \'users\' where email = ?', values: ['example@mail.com']});
});
test('should be able to parse to colons', () => {
const query = sql`select * from 'users' where email = ${'example@mail.com'}`.formatColon();
assert.equal(query, {sql: 'select * from \'users\' where email = :1', values: ['example@mail.com']});
});
test('should be able to parse to @p', () => {
const query = sql`select * from 'users' where email = ${'example@mail.com'}`.formatAtP();
assert.equal(query, {sql: 'select * from \'users\' where email = @p1', values: ['example@mail.com']});
});
test.run();

32
tsconfig.json Normal file
View File

@ -0,0 +1,32 @@
{
"ts-node": {
"compilerOptions": {
"module": "commonjs"
},
"include": [
"tests/**/*"
]
},
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"target": "es2015",
"module": "ESNext",
"declaration": true,
"types": ["node"],
"preserveSymlinks": true,
"isolatedModules": true,
"esModuleInterop": true,
"downlevelIteration": true,
"noUnusedLocals": true,
"noImplicitAny": true,
"noUnusedParameters": true,
"preserveConstEnums": true,
"skipLibCheck": true,
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"allowSyntheticDefaultImports": true
},
"exclude": ["test", "dist"]
}

1458
yarn.lock Normal file

File diff suppressed because it is too large Load Diff