Add example service as well as data source for duckdb.master
@@ -9,8 +9,8 @@ type DeleteResult = unknown; | |||
export interface DataSource< | |||
ItemData extends object = object, | |||
ID extends unknown = unknown, | |||
Query extends object = object, | |||
ID extends string = string | |||
> { | |||
initialize(): Promise<unknown>; | |||
getTotalCount?(query?: Query): Promise<TotalCount>; | |||
@@ -0,0 +1,107 @@ | |||
# Logs | |||
logs | |||
*.log | |||
npm-debug.log* | |||
yarn-debug.log* | |||
yarn-error.log* | |||
lerna-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/ | |||
# TypeScript v1 declaration files | |||
typings/ | |||
# 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.production | |||
.env.development | |||
# parcel-bundler cache (https://parceljs.org/) | |||
.cache | |||
# Next.js build output | |||
.next | |||
# 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 | |||
.npmrc |
@@ -0,0 +1,7 @@ | |||
MIT License Copyright (c) 2024 TheoryOfNekomata <allan.crisostomo@outlook.com> | |||
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 (including the next paragraph) 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. |
@@ -0,0 +1,67 @@ | |||
{ | |||
"name": "@modal-sh/yasumi-data-source-duckdb", | |||
"version": "0.0.0", | |||
"files": [ | |||
"dist", | |||
"src" | |||
], | |||
"engines": { | |||
"node": ">=16" | |||
}, | |||
"license": "MIT", | |||
"keywords": [ | |||
"pridepack" | |||
], | |||
"devDependencies": { | |||
"@types/node": "^20.11.0", | |||
"pridepack": "2.6.0", | |||
"tslib": "^2.6.2", | |||
"typescript": "^5.3.3", | |||
"vitest": "^1.2.0" | |||
}, | |||
"dependencies": { | |||
"@modal-sh/yasumi": "*", | |||
"duckdb-async": "^0.10.0" | |||
}, | |||
"scripts": { | |||
"prepublishOnly": "pridepack clean && pridepack build", | |||
"build": "pridepack build", | |||
"type-check": "pridepack check", | |||
"clean": "pridepack clean", | |||
"watch": "pridepack watch", | |||
"start": "pridepack start", | |||
"dev": "pridepack dev", | |||
"test": "vitest" | |||
}, | |||
"private": false, | |||
"description": "DuckDB adapter for Yasumi.", | |||
"repository": { | |||
"url": "", | |||
"type": "git" | |||
}, | |||
"homepage": "", | |||
"bugs": { | |||
"url": "" | |||
}, | |||
"author": "TheoryOfNekomata <allan.crisostomo@outlook.com>", | |||
"publishConfig": { | |||
"access": "public" | |||
}, | |||
"types": "./dist/types/index.d.ts", | |||
"main": "./dist/cjs/production/index.js", | |||
"module": "./dist/esm/production/index.js", | |||
"exports": { | |||
".": { | |||
"development": { | |||
"require": "./dist/cjs/development/index.js", | |||
"import": "./dist/esm/development/index.js" | |||
}, | |||
"require": "./dist/cjs/production/index.js", | |||
"import": "./dist/esm/production/index.js", | |||
"types": "./dist/types/index.d.ts" | |||
} | |||
}, | |||
"typesVersions": { | |||
"*": {} | |||
} | |||
} |
@@ -0,0 +1,3 @@ | |||
{ | |||
"target": "es2018" | |||
} |
@@ -0,0 +1,215 @@ | |||
import { Resource, validation as v, BaseResourceType } from '@modal-sh/yasumi'; | |||
import { DataSource, ResourceIdConfig } from '@modal-sh/yasumi/backend'; | |||
import { Database } from 'duckdb-async'; | |||
import assert from 'assert'; | |||
type ID = number; | |||
export const AutoincrementIdConfig = { | |||
// TODO | |||
generationStrategy: async () => {}, | |||
schema: v.number(), | |||
serialize: (v: unknown) => v?.toString() ?? '', | |||
deserialize: (v: string) => Number(v), | |||
} | |||
export class DuckDbDataSource< | |||
Schema extends v.BaseSchema = v.BaseSchema, | |||
CurrentName extends string = string, | |||
CurrentRouteName extends string = string, | |||
Data extends object = v.Output<Schema>, | |||
> implements DataSource<Data, ID> { | |||
private resource?: Resource<BaseResourceType & { | |||
schema: Schema, | |||
name: CurrentName, | |||
routeName: CurrentRouteName, | |||
}>; | |||
db?: Database; | |||
constructor() { | |||
// noop | |||
} | |||
async initialize() { | |||
assert(typeof this.resource !== 'undefined'); | |||
const idConfig = this.resource.state.shared.get('idConfig') as ResourceIdConfig<any> | undefined; | |||
assert(typeof idConfig !== 'undefined'); | |||
const idAttr = this.resource.state.shared.get('idAttr'); | |||
assert(typeof idAttr === 'string'); | |||
const idSchema = idConfig.schema as v.BaseSchema; | |||
this.db = await Database.create('test.db'); | |||
const clause = `CREATE TABLE IF NOT EXISTS ${this.resource.state.routeName}`; | |||
const resourceSchema = this.resource.schema as unknown as v.ObjectSchema<any>; | |||
const tableSchema = Object.entries(resourceSchema.entries) | |||
.map(([columnName, columnDefRaw]) => { | |||
const columnDef = columnDefRaw as unknown as v.BaseSchema; | |||
return [columnName, columnDef.type].join(' '); | |||
}) | |||
.join(','); | |||
const sql = `${clause} (${idAttr} ${idSchema.type}, ${tableSchema});`; | |||
const con = await this.db.connect(); | |||
const stmt = await con.prepare(sql); | |||
await stmt.run(); | |||
} | |||
prepareResource<Schema extends v.BaseSchema>(resource: Resource<BaseResourceType & { | |||
schema: Schema, | |||
name: CurrentName, | |||
routeName: CurrentRouteName, | |||
}>) { | |||
resource.dataSource = resource.dataSource ?? this; | |||
const originalResourceId = resource.id; | |||
resource.id = <NewIdAttr extends BaseResourceType['idAttr'], NewIdSchema extends BaseResourceType['idSchema']>(newIdAttr: NewIdAttr, params: ResourceIdConfig<NewIdSchema>) => { | |||
originalResourceId(newIdAttr, params); | |||
return resource as Resource<BaseResourceType & { | |||
name: CurrentName, | |||
routeName: CurrentRouteName, | |||
schema: Schema, | |||
idAttr: NewIdAttr, | |||
idSchema: NewIdSchema, | |||
}>; | |||
}; | |||
this.resource = resource as any; | |||
} | |||
async getMultiple() { | |||
assert(typeof this.db !== 'undefined'); | |||
assert(typeof this.resource !== 'undefined'); | |||
const con = await this.db.connect(); | |||
const stmt = await con.prepare(` | |||
SELECT * FROM ${this.resource.state.routeName}; | |||
`); | |||
const data = await stmt.all(); | |||
return data as Data[]; | |||
} | |||
async newId() { | |||
const idConfig = this.resource?.state.shared.get('idConfig') as ResourceIdConfig<any>; | |||
assert(typeof idConfig !== 'undefined'); | |||
const theNewId = await idConfig.generationStrategy(this); | |||
return theNewId as ID; | |||
} | |||
async create(data: Data) { | |||
assert(typeof this.db !== 'undefined'); | |||
assert(typeof this.resource !== 'undefined'); | |||
const idConfig = this.resource.state.shared.get('idConfig') as ResourceIdConfig<any> | undefined; | |||
assert(typeof idConfig !== 'undefined'); | |||
const idAttr = this.resource.state.shared.get('idAttr'); | |||
assert(typeof idAttr === 'string'); | |||
const { [idAttr]: _, ...effectiveData } = data as Record<string, unknown>; | |||
const clause = `INSERT INTO ${this.resource.state.routeName}`; | |||
const keys = Object.keys(effectiveData).join(','); | |||
const values = Object.values(effectiveData).map((d) => JSON.stringify(d).replace(/"/g, "'")).join(','); | |||
const sql = `${clause} (${keys}) VALUES (${values});`; | |||
const con = await this.db.connect(); | |||
const stmt = await con.prepare(sql); | |||
await stmt.all(); | |||
const newData = { | |||
...effectiveData | |||
}; | |||
return newData as Data; | |||
} | |||
async getTotalCount() { | |||
assert(typeof this.db !== 'undefined'); | |||
assert(typeof this.resource !== 'undefined'); | |||
const idAttr = this.resource.state.shared.get('idAttr'); | |||
assert(typeof idAttr === 'string'); | |||
const con = await this.db.connect(); | |||
const stmt = await con.prepare(` | |||
SELECT COUNT(*) FROM ?; | |||
`, this.resource.state.routeName); | |||
const [data] = await stmt.all(); | |||
return data as unknown as number; | |||
} | |||
async getById(id: ID) { | |||
assert(typeof this.db !== 'undefined'); | |||
assert(typeof this.resource !== 'undefined'); | |||
const idAttr = this.resource.state.shared.get('idAttr'); | |||
assert(typeof idAttr === 'string'); | |||
const con = await this.db.connect(); | |||
const stmt = await con.prepare(` | |||
SELECT * FROM ? WHERE ? = ?; | |||
`, this.resource.state.routeName, idAttr, id); | |||
const data = await stmt.all(); | |||
return data as Data; | |||
} | |||
async getSingle() { | |||
assert(typeof this.db !== 'undefined'); | |||
assert(typeof this.resource !== 'undefined'); | |||
const con = await this.db.connect(); | |||
const stmt = await con.prepare(` | |||
SELECT * FROM ? LIMIT 1; | |||
`, this.resource.state.routeName); | |||
const [data] = await stmt.all(); | |||
return data as Data; | |||
} | |||
async delete(id: ID) { | |||
assert(typeof this.db !== 'undefined'); | |||
assert(typeof this.resource !== 'undefined'); | |||
const idAttr = this.resource.state.shared.get('idAttr'); | |||
assert(typeof idAttr === 'string'); | |||
const con = await this.db.connect(); | |||
const stmt = await con.prepare(` | |||
DELETE FROM ? WHERE ? = ?; | |||
`, this.resource.state.routeName, idAttr, id); | |||
await stmt.run(); | |||
} | |||
async emplace(id: ID, data: Data) { | |||
assert(typeof this.db !== 'undefined'); | |||
assert(typeof this.resource !== 'undefined'); | |||
const idAttr = this.resource.state.shared.get('idAttr'); | |||
assert(typeof idAttr === 'string'); | |||
const con = await this.db.connect(); | |||
const stmt = await con.prepare(` | |||
INSERT OR REPLACE INTO ? (?, ...?) VALUES (...?); | |||
`, this.resource.state.routeName, id, Object.keys(data), Object.values(data)); | |||
const [newData] = await stmt.all(); | |||
// TODO check if created flag | |||
return [newData, false] as [Data, boolean]; | |||
} | |||
async patch(id: ID, data: Partial<Data>) { | |||
assert(typeof this.db !== 'undefined'); | |||
assert(typeof this.resource !== 'undefined'); | |||
const idAttr = this.resource.state.shared.get('idAttr'); | |||
assert(typeof idAttr === 'string'); | |||
const con = await this.db.connect(); | |||
const stmt = await con.prepare(` | |||
UPDATE ? SET ? = ? WHERE ? = ?; | |||
`, | |||
this.resource.state.routeName, | |||
Object.keys(data), Object.values(data), | |||
idAttr, id | |||
); | |||
const [newData] = await stmt.all(); | |||
return newData as Data; | |||
} | |||
} |
@@ -0,0 +1,8 @@ | |||
import { describe, it, expect } from 'vitest'; | |||
import add from '../src'; | |||
describe('blah', () => { | |||
it('works', () => { | |||
expect(add(1, 1)).toEqual(2); | |||
}); | |||
}); |
@@ -0,0 +1,23 @@ | |||
{ | |||
"exclude": ["node_modules"], | |||
"include": ["src", "types"], | |||
"compilerOptions": { | |||
"module": "ESNext", | |||
"lib": ["ESNext"], | |||
"importHelpers": true, | |||
"declaration": true, | |||
"sourceMap": true, | |||
"rootDir": "./src", | |||
"strict": true, | |||
"noUnusedLocals": true, | |||
"noUnusedParameters": true, | |||
"noImplicitReturns": true, | |||
"noFallthroughCasesInSwitch": true, | |||
"moduleResolution": "bundler", | |||
"jsx": "react", | |||
"esModuleInterop": true, | |||
"target": "es2018", | |||
"useDefineForClassFields": false, | |||
"declarationMap": true | |||
} | |||
} |
@@ -6,6 +6,7 @@ import { constants } from 'http2'; | |||
import TAGALOG from './languages/tl'; | |||
const UuidIdConfig = { | |||
// TODO bind to data source | |||
generationStrategy: () => Promise.resolve(randomUUID()), | |||
schema: v.string(), | |||
serialize: (v: unknown) => v?.toString() ?? '', | |||
@@ -0,0 +1,107 @@ | |||
# Logs | |||
logs | |||
*.log | |||
npm-debug.log* | |||
yarn-debug.log* | |||
yarn-error.log* | |||
lerna-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/ | |||
# TypeScript v1 declaration files | |||
typings/ | |||
# 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.production | |||
.env.development | |||
# parcel-bundler cache (https://parceljs.org/) | |||
.cache | |||
# Next.js build output | |||
.next | |||
# 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 | |||
.npmrc |
@@ -0,0 +1,50 @@ | |||
{ | |||
"name": "@modal-sh/yasumi-example-duckdb", | |||
"version": "0.0.0", | |||
"files": [ | |||
"dist", | |||
"src" | |||
], | |||
"engines": { | |||
"node": ">=16" | |||
}, | |||
"keywords": [ | |||
"pridepack" | |||
], | |||
"devDependencies": { | |||
"@types/node": "^20.11.0", | |||
"pridepack": "2.6.0", | |||
"tslib": "^2.6.2", | |||
"typescript": "^5.3.3", | |||
"vitest": "^1.2.0" | |||
}, | |||
"dependencies": { | |||
"@modal-sh/yasumi": "*", | |||
"@modal-sh/yasumi-data-source-duckdb": "*", | |||
"tsx": "^4.7.1" | |||
}, | |||
"scripts": { | |||
"prepublishOnly": "pridepack clean && pridepack build", | |||
"build": "pridepack build", | |||
"type-check": "pridepack check", | |||
"clean": "pridepack clean", | |||
"watch": "pridepack watch", | |||
"start": "tsx src/index.ts", | |||
"dev": "tsx watch src/index.ts", | |||
"test": "vitest" | |||
}, | |||
"private": true, | |||
"description": "DuckDB-powered example service.", | |||
"repository": { | |||
"url": "", | |||
"type": "git" | |||
}, | |||
"homepage": "", | |||
"bugs": { | |||
"url": "" | |||
}, | |||
"author": "TheoryOfNekomata <allan.crisostomo@outlook.com>", | |||
"publishConfig": { | |||
"access": "restricted" | |||
} | |||
} |
@@ -0,0 +1,3 @@ | |||
{ | |||
"target": "es2018" | |||
} |
@@ -0,0 +1,48 @@ | |||
import { resource, application, validation as v } from '@modal-sh/yasumi'; | |||
import { http } from '@modal-sh/yasumi/backend'; | |||
import { DuckDbDataSource, AutoincrementIdConfig } from '@modal-sh/yasumi-data-source-duckdb'; | |||
import { constants } from 'http2'; | |||
const Post = resource( | |||
v.object({ | |||
title: v.string(), | |||
content: v.string(), | |||
}) | |||
) | |||
.name('Post') | |||
.route('posts') | |||
.id('id', AutoincrementIdConfig) | |||
.createdAt('createdAt') | |||
.updatedAt('updatedAt') | |||
.canFetchItem() | |||
.canFetchCollection() | |||
.canCreate() | |||
.canEmplace() | |||
.canPatch() | |||
.canDelete(); | |||
const app = application({ | |||
name: 'duckdb-service' | |||
}) | |||
.resource(Post); | |||
const backend = app.createBackend({ | |||
dataSource: new DuckDbDataSource(), | |||
}) | |||
.throwsErrorOnDeletingNotFound(); | |||
const server = backend.createHttpServer({ | |||
basePath: '/api', | |||
}) | |||
.defaultErrorHandler((_req, res) => () => { | |||
throw new http.ErrorPlainResponse('urlNotFound', { | |||
statusCode: constants.HTTP_STATUS_NOT_FOUND, | |||
res, | |||
}); | |||
// throw new http.ErrorPlainResponse('notImplemented', { | |||
// statusCode: constants.HTTP_STATUS_NOT_IMPLEMENTED, | |||
// res, | |||
// }); | |||
}); | |||
server.listen(6969); |
@@ -0,0 +1,23 @@ | |||
{ | |||
"exclude": ["node_modules"], | |||
"include": ["src", "types"], | |||
"compilerOptions": { | |||
"module": "ESNext", | |||
"lib": ["ESNext"], | |||
"importHelpers": true, | |||
"declaration": true, | |||
"sourceMap": true, | |||
"rootDir": "./src", | |||
"strict": true, | |||
"noUnusedLocals": true, | |||
"noUnusedParameters": true, | |||
"noImplicitReturns": true, | |||
"noFallthroughCasesInSwitch": true, | |||
"moduleResolution": "bundler", | |||
"jsx": "react", | |||
"esModuleInterop": true, | |||
"target": "es2018", | |||
"useDefineForClassFields": false, | |||
"declarationMap": true | |||
} | |||
} |