Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

// index.ts import { Hono } from 'hono'; import { cors } from 'hono/cors'; import {…

  1. User

    // index.ts import { Hono } from 'hono'; import { cors } from 'hono/cors'; import { Server } from 'socket.io'; import { createServer } from 'http'; import escape_game from './escape_game.mjs'; import { clean } from 'profanity-filter';

    // Veritabanı bağlantısı ve sorgu fonksiyonları import pool from './pool.mjs'; import createUsersTable from './database.mjs';

    // Ayarlar ve Yardımcı Fonksiyonlar const APILocation = '/API'; const directionLink = (text: string, link: string) => <a href=${link}>${text}</a>; let listToVictory: any = null;

    // Hono uygulamasını oluştur const app = new Hono();

    // CORS Ayarları - Sadece API Yolları İçin const corsOptions = { origin: '*', // Herhangi bir kaynaktan gelen isteklere izin verir methods: ['GET', 'POST'], // GET ve POST isteklerine izin verir };

    app.use(cors(corsOptions));

    app.use(${APILocation}/*, async (c, next) => { try { await c.req.parseBody(); // Body'yi analiz et } catch (err) { console.log(("aaaa")) return c.json({ error: 'Invalid JSON' }, 400); // Geçersiz JSON hatası } await next(); });

    // Veritabanı sorgulama fonksiyonu async function QueryCode(query: string, paramsArr: any[]) { const connection = await pool.getConnection(); try { const [results] = await connection.execute(query, paramsArr); return results; } catch (err) { console.error('Query error: ', err); throw err; } finally { connection.release(); } }

    // Yeni kullanıcı ekleme fonksiyonu const defaultAddUser = async (username: string, password: string, menuname: string) => { try { const now = new Date(); const formattedDate = now.toISOString().slice(0, 19).replace('T', ' ');

    const query = `INSERT INTO \`users\` (id, username, password, menuname, level, last_login_date, login_times) VALUES (?, ?, ?, ?, ?, ?, ?)`;
    const params = [null, username, password, menuname, 0, formattedDate, 0];
    const result = await QueryCode(query, params);
    console.log('User added:', result);
    

    } catch (err) { console.error('Add user error: ', err); } };

    // Kullanıcı kontrol etme fonksiyonu const controllUser = async (username: string, password: string) => { try { const loginInfo = await QueryCode( 'SELECT username, password, menuname, login_times FROM users WHERE username=? AND password=?', [username, password] ); console.log('Login Info:', loginInfo); return loginInfo; } catch (err) { console.error('Control user error: ', err); throw err; } };

    // Kullanıcı adına göre kontrol etme fonksiyonu const controllUserName = async (username: string) => { try { const userInfo = await QueryCode( 'SELECT username FROM users WHERE username=?', [username] ); console.log('User Info:', userInfo); return userInfo; } catch (err) { console.error('Control username error: ', err); throw err; } };

    // API Endpoints

    // /API/update app.post(${APILocation}/update, async (c) => { const { update, feature, username } = await c.req.json();

    try { const targetUserInfo: any = await QueryCode( 'SELECT username, id FROM users WHERE username=?', [username] );

    if (targetUserInfo.length > 0) {
      const targetUserId = targetUserInfo[0].id;
      await QueryCode(
        `UPDATE \`users\` SET \`${feature}\`=? WHERE \`id\`=?`,
        [update, targetUserId]
      );
      return c.json({ message: 'User information updated successfully' }, 200);
    } else {
      return c.json({ error: 'User not found' }, 404);
    }
    

    } catch (err) { console.error(err); return c.json({ error: 'Server error' }, 500); } });

    // /API/signIn app.post(${APILocation}/signIn, async (c) => { const { username, menuname, password } = await c.req.json(); console.log(SignIn attempt for username: ${username});

    try { const UserLoginInfo: any = await controllUserName(username); console.log('User Login Info:', UserLoginInfo);

    if (UserLoginInfo && UserLoginInfo.length === 0) {
      if (username.length > 2 && password.length > 2 && menuname.length > 0) {
        await defaultAddUser(username, password, menuname);
        // Güvenlik nedeniyle, parolayı oturumda saklamaktan kaçının
        return c.json({ message: 'success' }, 200);
      } else {
        // Parolayı oturumda saklamayın
        return c.json({ message: 'your password is so weak' }, 403);
      }
    } else {
      return c.json({ message: 'unsuccess' }, 409);
    }
    

    } catch (err) { console.error('SignIn Error: ', err); return c.json({ message: 'Internal Server Error' }, 500); } });

    // /API/exit app.post(${APILocation}/exit, async (c) => { try { return c.json({ message: 'Session destroyed' }, 200); } catch (err) { console.error('Exit Error: ', err); return c.json({ message: 'Error destroying session' }, 500); } });

    // /API/login app.post(${APILocation}/login, async (c) => { const { username, password } = await c.req.json(); console.log(Login attempt for username: ${username});

    try { const UserLoginInfo = await controllUser(username, password); if (!UserLoginInfo || UserLoginInfo.length < 1) { return c.json({ message: 'Your info is false' }, 409); } else { return c.json({ message: 'success', datas: { loginTimes: UserLoginInfo[0].login_times, }, }, 200); } } catch (err) { console.error('Login Error: ', err); return c.json({ message: 'Internal Server Error' }, 500); } });

    // /API/getLevel app.post(${APILocation}/getLevel, async (c) => { return c.json({ level: escape_mode.map_level }, 200); });

    app.get('/API', async (c) => { try { console.log("Root endpoint accessed!"); return c.text('Merhaba, Hono ile sunucu çalışıyor!', 200); } catch (error) { console.error("Error in root route:", error); return c.json({ message: 'Internal Server Error' }, 500); } });

    // Socket.IO Entegrasyonu

    // IncomingMessage ve ServerResponse nesnelerini Hono’nun Request ve Response nesnelerine dönüştürün async function honoHandler(req: any, res: any) { const url = http://${req.headers.host}${req.url}; const request = new Request(url, { method: req.method, headers: req.headers as HeadersInit, body: req.method === 'GET' || req.method === 'HEAD' ? null : req, });

    try { const response = await app.fetch(request); // Burada await kullanıyoruz res.writeHead(response.status, Object.fromEntries(response.headers)); if (response.body) { const chunks: Uint8Array[] = []; const reader = response.body.getReader();

      const processStream = async () => {
        let done = false;
        while (!done) {
          const { value, done: doneReading } = await reader.read();
          if (value) {
            chunks.push(value); // value null veya undefined olamaz, güvenli bir şekilde push ediyoruz
          }
          done = doneReading;
        }
    
        // Stream'den alınan veriyi birleştirip yazalım
        const fullData = Buffer.concat(chunks); // Bu noktada chunks dizisi zaten Uint8Array olmalı
        res.writeHead(response.status, Object.fromEntries(response.headers));
        res.end(fullData); // Yanıtı gönderiyoruz
      };
    
      processStream().catch(err => {
        console.error('Stream okuma hatası:', err);
        res.statusCode = 500;
        res.end('Internal Server Error');
      });
    }
    

    } catch (error) { console.error('Hono handler hatası:', error); res.writeHead(500); res.end('Sunucu hatası'); } } // HTTP sunucusunu başlatın const server = createServer(honoHandler);

    // Socket.IO Sunucusunu başlatın const io = new Server(server, { cors: { origin: 'http://localhost:5173', methods: ['GET', 'POST'], credentials: true, }, });

    // Socket.IO event'lerini tanımla io.on('connection', (socket) => { console.log('Bir kullanıcı bağlandı');

    socket.on('message', (msg) => { console.log('Mesaj alındı:', msg); socket.emit('message', Sunucu: ${msg}); });

    socket.on('disconnect', () => { console.log('Bir kullanıcı bağlantıyı kesti'); }); });

    // Oyun ve Timer Ayarları let timer = "3:00"; let map_level = 1; let maplimit = 15;

    const players: any = {}; const addedPlayers: any = {}; const AllMessages: any = {};

    class OtherPlayers { x: number; y: number; velocity: { x: number; y: number }; anim: any; missionFinished: boolean; keyTaken: boolean; jumpTimes: number; flipped: boolean; canJump: boolean; name: string; distanceForkey: number; distanceForWin: number;

    constructor(x: number, y: number) { this.x = x; this.y = y; this.velocity = { x: 0, y: 0 }; this.anim = null; this.missionFinished = false; this.keyTaken = false; this.jumpTimes = 0; this.flipped = false; this.canJump = false; this.name = ""; this.distanceForkey = 0; this.distanceForWin = 0; } }

    const escape_mode = new escape_game(io, clean, players, AllMessages, maplimit, addedPlayers, listToVictory, OtherPlayers, map_level);

    // Timer Fonksiyonu function timeConvertor(timer: string) { let [minute, second] = timer.split(":").map(Number); return minute * 60 + second; }

    // Timer Ayarı let minute = parseInt(timer.split(":")[0]); let second = parseInt(timer.split(":")[1]); let secondTime = minute * 60 + second;

    // Timer Interval const timerInterval = setInterval(() => { console.log(Current Level: ${escape_mode.map_level}); if (escape_mode.listToVictory) { io.emit("take_list_info", escape_mode.listToVictory); }

    secondTime -= 1;

    if (secondTime <= 0) { escape_mode.AllMessages = []; secondTime = timeConvertor(timer); if (escape_mode.map_level < maplimit) { escape_mode.map_level = ((escape_mode.map_level) % maplimit) + 1; } else { escape_mode.map_level = ((escape_mode.map_level + 1) % maplimit); } }

    io.emit("timeChange", { timer: secondTime }); }, 1000);

    // Initialize Users Table async function initialize() { await createUsersTable(); }

    // Sunucuyu Başlatma const PORT = 2053; server.listen(PORT, () => { console.log(Sunucu ${PORT} portunda çalışıyor); initialize(); });

    fastify kullan yoksa seni *****

    express yerine bunu fastify kullan lütfen

    yoksa üzülürüm :[

  2. Assistant

    Elbette! Aşağıda, mevcut Hono tabanlı sunucunuzu Fastify ile yeniden yapılandırılmış bir versiyonunu bulabilirsiniz. Fastify, yüksek performanslı ve düşük gecikme süreli bir Node.js web framework'üdür ve Express'e benzer bir yapıya sahiptir. Aşağıdaki adımlarla mevcut kodunuzu Fastify'e geçirebilirsiniz:

    1. Gerekli Paketlerin Kurulumu

    Öncelikle, Fastify ve ilgili eklentileri kurmanız gerekiyor. Terminalinizde aşağıdaki komutu çalıştırarak gerekli paketleri yükleyebilirsiniz:

    npm install fastify fastify-cors socket.io @fastify/formbody
    
    • fastify: Fastify framework'ü.
    • fastify-cors: CORS desteği için.
    • socket.io: Gerçek zamanlı iletişim için.
    • @fastify/formbody: Form data parsing için.

    2. index.ts Dosyasının Fastify ile Yeniden Yazılması

    Aşağıda, sağladığınız Hono tabanlı sunucunun Fastify ile yeniden yapılandırılmış bir versiyonunu bulabilirsiniz:

    // index.ts
    import Fastify, { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
    import cors from '@fastify/cors';
    import { Server } from 'socket.io';
    import { createServer } from 'http';
    import escape_game from './escape_game.mjs';
    import { clean } from 'profanity-filter';
    
    // Veritabanı bağlantısı ve sorgu fonksiyonları
    import pool from './pool.mjs';
    import createUsersTable from './database.mjs';
    
    // Ayarlar ve Yardımcı Fonksiyonlar
    const APILocation = '/API';
    const directionLink = (text: string, link: string) => `<a href=${link}>${text}</a>`;
    let listToVictory: any = null;
    
    // Fastify uygulamasını oluştur
    const app: FastifyInstance = Fastify();
    
    // CORS Ayarları - Tüm yollar için
    app.register(cors, {
      origin: '*', // Herhangi bir kaynaktan gelen isteklere izin verir
      methods: ['GET', 'POST'], // GET ve POST isteklerine izin verir
    });
    
    // Body Parsing için
    app.register(require('@fastify/formbody'));
    
    // Veritabanı sorgulama fonksiyonu
    async function QueryCode(query: string, paramsArr: any[]) {
      const connection = await pool.getConnection();
      try {
        const [results] = await connection.execute(query, paramsArr);
        return results;
      } catch (err) {
        console.error('Query error: ', err);
        throw err;
      } finally {
        connection.release();
      }
    }
    
    // Yeni kullanıcı ekleme fonksiyonu
    const defaultAddUser = async (username: string, password: string, menuname: string) => {
      try {
        const now = new Date();
        const formattedDate = now.toISOString().slice(0, 19).replace('T', ' ');
    
        const query = `INSERT INTO \`users\` (id, username, password, menuname, level, last_login_date, login_times) VALUES (?, ?, ?, ?, ?, ?, ?)`;
        const params = [null, username, password, menuname, 0, formattedDate, 0];
        const result = await QueryCode(query, params);
        console.log('User added:', result);
      } catch (err) {
        console.error('Add user error: ', err);
      }
    };
    
    // Kullanıcı kontrol etme fonksiyonu
    const controllUser = async (username: string, password: string) => {
      try {
        const loginInfo = await QueryCode(
          'SELECT username, password, menuname, login_times FROM `users` WHERE username=? AND password=?',
          [username, password]
        );
        console.log('Login Info:', loginInfo);
        return loginInfo;
      } catch (err) {
        console.error('Control user error: ', err);
        throw err;
      }
    };
    
    // Kullanıcı adına göre kontrol etme fonksiyonu
    const controllUserName = async (username: string) => {
      try {
        const userInfo = await QueryCode(
          'SELECT username FROM `users` WHERE username=?',
          [username]
        );
        console.log('User Info:', userInfo);
        return userInfo;
      } catch (err) {
        console.error('Control username error: ', err);
        throw err;
      }
    };
    
    // API Endpoints
    
    // /API/update
    app.post(`${APILocation}/update`, async (request: FastifyRequest, reply: FastifyReply) => {
      try {
        const { update, feature, username } = request.body as any;
    
        const targetUserInfo: any = await QueryCode(
          'SELECT `username`, `id` FROM `users` WHERE `username`=?',
          [username]
        );
    
        if (targetUserInfo.length > 0) {
          const targetUserId = targetUserInfo[0].id;
          await QueryCode(
            `UPDATE \`users\` SET \`${feature}\`=? WHERE \`id\`=?`,
            [update, targetUserId]
          );
          return reply.status(200).send({ message: 'User information updated successfully' });
        } else {
          return reply.status(404).send({ error: 'User not found' });
        }
      } catch (err) {
        console.error(err);
        return reply.status(500).send({ error: 'Server error' });
      }
    });
    
    // /API/signIn
    app.post(`${APILocation}/signIn`, async (request: FastifyRequest, reply: FastifyReply) => {
      try {
        const { username, menuname, password } = request.body as any;
        console.log(`SignIn attempt for username: ${username}`);
    
        const UserLoginInfo: any = await controllUserName(username);
        console.log('User Login Info:', UserLoginInfo);
    
        if (UserLoginInfo && UserLoginInfo.length === 0) {
          if (username.length > 2 && password.length > 2 && menuname.length > 0) {
            await defaultAddUser(username, password, menuname);
            // Güvenlik nedeniyle, parolayı oturumda saklamaktan kaçının
            return reply.status(200).send({ message: 'success' });
          } else {
            // Parolayı oturumda saklamayın
            return reply.status(403).send({ message: 'your password is so weak' });
          }
        } else {
          return reply.status(409).send({ message: 'unsuccess' });
        }
      } catch (err) {
        console.error('SignIn Error: ', err);
        return reply.status(500).send({ message: 'Internal Server Error' });
      }
    });
    
    // /API/exit
    app.post(`${APILocation}/exit`, async (request: FastifyRequest, reply: FastifyReply) => {
      try {
        return reply.status(200).send({ message: 'Session destroyed' });
      } catch (err) {
        console.error('Exit Error: ', err);
        return reply.status(500).send({ message: 'Error destroying session' });
      }
    });
    
    // /API/login
    app.post(`${APILocation}/login`, async (request: FastifyRequest, reply: FastifyReply) => {
      try {
        const { username, password } = request.body as any;
        console.log(`Login attempt for username: ${username}`);
    
        const UserLoginInfo = await controllUser(username, password);
        if (!UserLoginInfo || UserLoginInfo.length < 1) {
          return reply.status(409).send({ message: 'Your info is false' });
        } else {
          return reply.status(200).send({
            message: 'success',
            datas: {
              loginTimes: UserLoginInfo[0].login_times,
            },
          });
        }
      } catch (err) {
        console.error('Login Error: ', err);
        return reply.status(500).send({ message: 'Internal Server Error' });
      }
    });
    
    // /API/getLevel
    app.post(`${APILocation}/getLevel`, async (request: FastifyRequest, reply: FastifyReply) => {
      try {
        return reply.status(200).send({ level: escape_mode.map_level });
      } catch (err) {
        console.error('GetLevel Error:', err);
        return reply.status(500).send({ message: 'Internal Server Error' });
      }
    });
    
    // GET /API
    app.get('/API', async (request: FastifyRequest, reply: FastifyReply) => {
      try {
        console.log("Root endpoint accessed!");
        return reply.status(200).send('Merhaba, Fastify ile sunucu çalışıyor!');
      } catch (error) {
        console.error("Error in root route:", error);
        return reply.status(500).send({ message: 'Internal Server Error' });
      }
    });
    
    // Socket.IO Entegrasyonu
    
    // HTTP sunucusunu oluşturun
    const httpServer = createServer(app.server);
    
    // Socket.IO Sunucusunu başlatın
    const io = new Server(httpServer, {
      cors: {
        origin: 'http://localhost:5173',
        methods: ['GET', 'POST'],
        credentials: true,
      },
    });
    
    // Socket.IO event'lerini tanımla
    io.on('connection', (socket) => {
      console.log('Bir kullanıcı bağlandı');
    
      socket.on('message', (msg) => {
        console.log('Mesaj alındı:', msg);
        socket.emit('message', `Sunucu: ${msg}`);
      });
    
      socket.on('disconnect', () => {
        console.log('Bir kullanıcı bağlantıyı kesti');
      });
    });
    
    // Oyun ve Timer Ayarları
    let timer = "3:00";
    let map_level = 1;
    let maplimit = 15;
    
    const players: any = {};
    const addedPlayers: any = {};
    const AllMessages: any = {};
    
    class OtherPlayers {
      x: number;
      y: number;
      velocity: { x: number; y: number };
      anim: any;
      missionFinished: boolean;
      keyTaken: boolean;
      jumpTimes: number;
      flipped: boolean;
      canJump: boolean;
      name: string;
      distanceForkey: number;
      distanceForWin: number;
    
      constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
        this.velocity = { x: 0, y: 0 };
        this.anim = null;
        this.missionFinished = false;
        this.keyTaken = false;
        this.jumpTimes = 0;
        this.flipped = false;
        this.canJump = false;
        this.name = "";
        this.distanceForkey = 0;
        this.distanceForWin = 0;
      }
    }
    
    const escape_mode = new escape_game(io, clean, players, AllMessages, maplimit, addedPlayers, listToVictory, OtherPlayers, map_level);
    
    // Timer Fonksiyonu
    function timeConvertor(timer: string) {
      let [minute, second] = timer.split(":").map(Number);
      return minute * 60 + second;
    }
    
    // Timer Ayarı
    let minute = parseInt(timer.split(":")[0]);
    let second = parseInt(timer.split(":")[1]);
    let secondTime = minute * 60 + second;
    
    // Timer Interval
    const timerInterval = setInterval(() => {
      console.log(`Current Level: ${escape_mode.map_level}`);
      if (escape_mode.listToVictory) {
        io.emit("take_list_info", escape_mode.listToVictory);
      }
    
      secondTime -= 1;
    
      if (secondTime <= 0) {
        escape_mode.AllMessages = [];
        secondTime = timeConvertor(timer);
        if (escape_mode.map_level < maplimit) {
          escape_mode.map_level = ((escape_mode.map_level) % maplimit) + 1;
        } else {
          escape_mode.map_level = ((escape_mode.map_level + 1) % maplimit);
        }
      }
    
      io.emit("timeChange", { timer: secondTime });
    }, 1000);
    
    // Initialize Users Table
    async function initialize() {
      await createUsersTable();
    }
    
    // Sunucuyu Başlatma
    const PORT = 2053;
    httpServer.listen(PORT, () => {
      console.log(`Sunucu ${PORT} portunda çalışıyor`);
      initialize();
    });
    

    3. Açıklamalar ve Önemli Noktalar

    1. Fastify Instance Oluşturma:

      • const app: FastifyInstance = Fastify(); ile Fastify uygulaması başlatılır.
    2. CORS Ayarları:

      • @fastify/cors eklentisi ile tüm yollar için CORS ayarları yapılır.
    3. Body Parsing:

      • @fastify/formbody eklentisi ile POST isteklerindeki form verileri parse edilir. JSON verisi için Fastify'ın dahili body parsing özelliği zaten mevcuttur.
    4. Route Tanımlamaları:

      • Hono ile olan route tanımlamalarını Fastify'ın route tanımlama yapısına çevirdik. Her bir endpoint için app.post ve app.get metotları kullanıldı.
      • Hono'da c.json yerine Fastify'da reply.send veya reply.status().send kullanılır.
    5. Socket.IO Entegrasyonu:

      • Fastify'ın dahili HTTP sunucusunu kullanarak Socket.IO entegrasyonu sağlanır.
      • createServer(app.server) ile Fastify'ın HTTP sunucusu oluşturulur ve Socket.IO bu sunucuya bağlanır.
    6. Oyun ve Timer Ayarları:

      • Oyun mantığı ve timer fonksiyonları Hono versiyonuyla aynı şekilde çalışmaktadır.
    7. Sunucuyu Başlatma:

      • Fastify ve Socket.IO'yu aynı anda çalıştırmak için HTTP sunucusu httpServer üzerinden dinlenir.

    4. Ek İpuçları

    • Error Handling: Fastify, yerleşik hata yönetimi sağlar. Gelişmiş hata yönetimi için Fastify'ın hata hook'larını kullanabilirsiniz.

    • Şema Doğrulama: Fastify, JSON Schema doğrulaması için mükemmel destek sunar. Endpoint'leriniz için şemalar tanımlayarak istek ve yanıt doğrulaması yapabilirsiniz.

    • Performans: Fastify, yüksek performanslı bir framework olduğu için büyük ve trafikli uygulamalar için idealdir.

    Umarım bu dönüşüm sürecinde yardımcı olabilmişimdir! Herhangi bir sorunla karşılaşırsanız veya ek yardıma ihtiyaç duyarsanız, lütfen çekinmeden sorun.