Open w3bdesign opened 1 month ago
To convert this into a Node.js Hono API for fetching chess puzzles, you'll need to create an API that reads the CSV file, parses it, and serves the puzzles. Here's a basic implementation:
import { Hono } from 'hono'
import { serve } from '@hono/node-server'
import fs from 'fs'
import csv from 'csv-parser'
import zlib from 'zlib'
const app = new Hono()
const puzzles = []
// Read and parse the CSV file
fs.createReadStream('lichess_db_puzzle.csv.zst')
.pipe(zlib.createUnzip())
.pipe(csv())
.on('data', (data) => puzzles.push(data))
.on('end', () => {
console.log(`Loaded ${puzzles.length} puzzles`)
})
// Get a random puzzle
app.get('/puzzle/random', (c) => {
const puzzle = puzzles[Math.floor(Math.random() * puzzles.length)]
return c.json(puzzle)
})
// Get a puzzle by ID
app.get('/puzzle/:id', (c) => {
const id = c.req.param('id')
const puzzle = puzzles.find(p => p.PuzzleId === id)
if (puzzle) {
return c.json(puzzle)
}
return c.json({ error: 'Puzzle not found' }, 404)
})
// Get puzzles by theme
app.get('/puzzles/theme/:theme', (c) => {
const theme = c.req.param('theme')
const matchingPuzzles = puzzles.filter(p => p.Themes.includes(theme))
return c.json(matchingPuzzles)
})
// Start the server
const port = 3000
console.log(`Server is running on port ${port}`)
serve({
fetch: app.fetch,
port
})
To use this code:
Install the required dependencies:
npm install hono @hono/node-server csv-parser
Make sure you have the lichess_db_puzzle.csv.zst
file in the same directory as your script.
Run the script with Node.js:
node your_script_name.js
This API provides three endpoints:
/puzzle/random
: Returns a random puzzle/puzzle/:id
: Returns a specific puzzle by ID/puzzles/theme/:theme
: Returns all puzzles with a specific themeNote that this implementation loads all puzzles into memory, which might not be efficient for such a large dataset. For a production environment, you'd want to consider:
Would you like me to explain or elaborate on any part of this code?
https://database.lichess.org/#puzzles