w3bdesign / chess-tutor

https://chess-tutor-nor.vercel.app
MIT License
0 stars 0 forks source link

Puzzles #202

Open w3bdesign opened 1 month ago

w3bdesign commented 1 month ago

https://database.lichess.org/#puzzles

w3bdesign commented 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:

  1. Install the required dependencies:

    npm install hono @hono/node-server csv-parser
  2. Make sure you have the lichess_db_puzzle.csv.zst file in the same directory as your script.

  3. Run the script with Node.js:

    node your_script_name.js

This API provides three endpoints:

Note 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:

  1. Using a database instead of loading all puzzles into memory.
  2. Implementing pagination for the theme-based search.
  3. Adding more robust error handling and input validation.
  4. Implementing caching to improve performance.

Would you like me to explain or elaborate on any part of this code?

w3bdesign commented 1 month ago

https://rapidapi.com/KeeghanM/api/chess-puzzles/playground/apiendpoint_177d3683-dcc4-4a7b-812a-884e259e1304