Blog

  • fong

    fong

    npm version

    A service framework of node gRPC.

    简介

    fong是一个完全用typescript编写的node gRPC框架, 可以基于它很方便地编写gRPC微服务应用. 一般是用来编写service层应用, 以供bff层或前端层等调用.

    优点

    1.纯typescript编写, typescript的好处不用多说了. 并且用户使用这个框架框架时, 查看定义都是ts源码, 用户使用框架感受不到type definition文件.
    2.效仿egg.js的『约定优于配置』原则, 按照统一的约定进行应用开发, 项目风格一致, 开发模式简单, 上手速度极快. 如果用过egg, 就会发现一切都是那么熟悉.

    对比

    目前能找到的开源node gRPC框架很少, 跟其中star稍微多点的mali简单对比一下:

    对比方面 mali fong
    项目风格约定
    定义查看跳转 definition 源代码
    编写语言 javascript typescript
    proto文件加载 仅能加载一个 按目录加载多个
    代码生成
    中间件
    配置
    日志
    controller加载
    service加载 即将支持, 目前可以自己import即可
    util加载 即将支持, 目前可以自己import即可
    入参校验 即将支持
    插件机制 打算支持
    更多功能 TBD

    示例

    示例项目

    github: https://github.com/xiaozhongliu/ts-rpc-seed

    运行服务

    使用vscode的话直接进F5调试typescript.
    或者:

    npm start

    测试请求

    ts-node tester
    # 或者:
    npm run tsc
    node dist/tester.js

    使用

    目录约定

    不同类型文件只要按以下目录放到相应的文件夹即可自动加载.

    root
    ├── proto
    |  └── greeter.proto
    ├── config
    |  ├── config.default.ts
    |  ├── config.dev.ts
    |  ├── config.test.ts
    |  ├── config.stage.ts
    |  └── config.prod.ts
    ├── midware
    |  └── logger.ts
    ├── controller
    |  └── greeter.ts
    ├── service
    |  └── sample.ts
    ├── util
    |  └── sample.ts
    └── typings
    |  ├── enum.ts
    |  └── indexed.d.ts
    ├── log
    |  ├── common.20190512.log
    |  ├── common.20190513.log
    |  ├── request.20190512.log
    |  └── request.20190513.log
    ├── app
    ├── package.json
    ├── tsconfig.json
    └── tslint.json

    入口文件

    import App from 'fong'
    new App().start()

    配置示例

    默认配置config.default.ts与环境配置config.<NODE_ENV>.ts是必须的, 运行时会合并.
    配置可从ctx.config和app.config获取.

    import { AppInfo, Config } from 'fong'
    
    export default (appInfo: AppInfo): Config => {
        return {
            // basic
            PORT: 50051,
    
            // log
            COMMON_LOG_PATH: `${appInfo.rootPath}/log/common`,
            REQUEST_LOG_PATH: `${appInfo.rootPath}/log/request`,
        }
    }

    中间件示例

    注: req没有放到ctx, 是为了方便在controller中支持强类型.

    import { Context } from 'fong'
    import 'dayjs/locale/zh-cn'
    import dayjs from 'dayjs'
    dayjs.locale('zh-cn')
    
    export default async (ctx: Context, req: object, next: Function) => {
        const start = dayjs()
        await next()
        const end = dayjs()
    
        ctx.logger.request({
            '@duration': end.diff(start, 'millisecond'),
            controller: `${ctx.controller}.${ctx.action}`,
            metedata: JSON.stringify(ctx.metadata),
            request: JSON.stringify(req),
            response: JSON.stringify(ctx.response),
        })
    }

    controller示例

    import { Controller, Context } from 'fong'
    import HelloReply from '../typings/greeter/HelloReply'
    
    export default class GreeterController extends Controller {
    
        async sayHello(ctx: Context, req: HelloRequest): Promise<HelloReply> {
            return new HelloReply(
                `Hello ${req.name}`,
            )
        }
    
        async sayGoodbye(ctx: Context, req: HelloRequest): Promise<HelloReply> {
            return new HelloReply(
                `Goodbye ${req.name}`,
            )
        }
    }

    日志

    日志文件:
    请求日志: ./log/request.<yyyyMMdd>.log
    其他日志: ./log/common.<yyyyMMdd>.log

    请求日志示例:

    {
        "@env": "dev",
        "@region": "unknown",
        "@timestamp": "2019-05-12T22:23:53.181Z",
        "@duration": 5,
        "controller": "Greeter.sayHello",
        "metedata": "{\"user-agent\":\"grpc-node/1.20.3 grpc-c/7.0.0 (osx; chttp2; godric)\"}",
        "request": "{\"name\":\"world\"}",
        "response": "{\"message\":\"Hello world\"}"
    }

    代码生成

    代码生成器还未单独封包, 现在放在示例应用的codegen目录下.

    使用方法:
    1.定义好契约proto, 确保格式化了内容.

    2.运行代码生成逻辑:

    ts-node codegen

    这样就会生成controller及相关请求/响应的interface/class, 未来会支持更多类型的文件的生成.

    3.从./codegen/dist目录将生成的controller文件移入./controller文件夹并开始编写方法内部逻辑.

    定义查看跳转

    Peek Definition直接指向源码.

    近期计划

    service加载

    service文件放到service文件夹即可自动加载. 通过ctx.<service>使用.

    util加载

    util文件放到util文件夹即可自动加载. 通过ctx.util.<function>使用.

    入参校验

    把在这里用的参数校验中间件搬过来, 用class-validator和class-transformer实现校验, 支持自动生成.

    应用内的request model将会类似:

    import { IsOptional, Length, Min, Max, IsBoolean } from 'class-validator'
    
    export default class IndexRequest {
        @Length(4, 8)
        @IsOptional()
        foo: string
    
        @Min(5)
        @Max(10)
        @IsOptional()
        bar: number
    
        @IsBoolean()
        @IsOptional()
        baz: boolean
    }

    框架内的validate midware将会类似:

    import { Context } from 'egg'
    import { validate } from 'class-validator'
    import { plainToClass } from 'class-transformer'
    
    import HomeIndexRequest from '../request/home/IndexRequest'
    import HomeValidateRequest from '../request/home/ValidateRequest'
    const typeMap = new Map([
        ['Home.index', HomeIndexRequest],
        ['Home.validate', HomeValidateRequest],
    ])
    
    export default async (ctx: Context, next: Function) => {
        const type = typeMap.get(ctx.routerName)
        const target = plainToClass(type, ctx.query)
        const errors = await validate(target)
    
        if (!errors.length) return next()
    
        ctx.body = {
            success: false,
            message: errors.map(error => ({
                field: error.property,
                prompt: error.constraints,
            })),
        }
    }
    Visit original content creator repository https://github.com/xiaozhongliu/fong
  • node-cars-rent-api

    Sistema de Gerenciamento de Carros

    Este projeto é um sistema de backend desenvolvido em Node.js com TypeScript, voltado para o gerenciamento de
    carros, incluindo cadastro e listagem de veículos, gerenciamento de aluguéis e devoluções, e funcionalidades
    relacionadas à recuperação de senha dos usuários.

    Funcionalidades

    • Cadastro de Carro: Permite o cadastro de novos carros, com validação de placa única e cadastro padrão em disponibilidade. Apenas usuários administradores podem cadastrar.
    • Listagem de Carros: Listagem de carros disponíveis com filtros por categoria, marca ou nome. Disponível sem necessidade de login.
    • Cadastro de Especificação no Carro: Adição de especificações a carros, restrito a veículos cadastrados e usuários administradores.
    • Cadastro de Imagens do Carro: Possibilidade de adicionar imagens aos carros, usando multer para upload. Acesso restrito a administradores.
    • Aluguel de Carro: Funcionalidade para cadastro de aluguéis com regras específicas de duração, disponibilidade e status do usuário.
    • Devolução de Carro: Permite a devolução de carros alugados, com ajustes automáticos de status e cálculo de tarifas e multas.
    • Listagem de Alugueis para Usuário: Usuários logados podem ver seus aluguéis.
    • Recuperação de Senha: Recurso para recuperação de senha via e-mail com link de expiração.

    Tecnologias Utilizadas

    • Node.js
    • TypeScript
    • Express (gerenciamento de rotas)
    • Multer (upload de arquivos)
    • Outras dependências conforme necessidade do projeto.

    Instalação e Execução

    Pré-requisitos

    • Node.js
    • npm ou yarn

    Passos para Instalação

    1. Clone o repositório:

      git clone [url-do-repositorio]
      cd [nome-do-projeto]
       npm install
       # ou
       yarn install
      npm start
       # ou
       yarn start
      

    Contribuições

    Para contribuir, siga os passos habituais de fork, criação de branch, commit e pull request.

    Visit original content creator repository
    https://github.com/PaoloProdossimoLopes/node-cars-rent-api

  • Godot Modules

    Godot Modules

    Godot Modules is a collection of modules developed in Godot 3.x. Current project version is Godot 3.3.0.

    Notice

    Development of Godot Modules has come to a halt. This project will be used as a reference for future projects. I’ve recently tried upgrading this project to Godot 4.x but after seeing what I would have to do to the hotkey manager scripts I just decided no lets not do that lol (not to mention the other scripts that have to be converted)

    Some things I learned from this project that I thought I should highlight here

    • Dependency Injection can get really messy and you may be better off having a all-in-one static GameManager class where everything is linked through your GameManager script. GameManager should not extend from Godot.Node as then you will see all the properties and functions from Godot.Node, rather all the linking should be done in a separate script called Linker or MainLinker
    • All of these “modules” don’t really feel modular at all, you can’t just copy out a folder and plop it in your own project without getting several other dependent nodes and scripts. I’m still not sure how to tackle this problem without creating duplicate assets
    • Multiplayer can make the codebase a confusing mess and it’s best to really take your time when implementing it
    • Really not the best idea to make your own wrapper classes when Godots still in beta because Godot is always pushing new breaking changes

    Table of Contents

    Why make this?

    I was thinking to myself, I want to make a bullet hell game, but I am also going to be making more then just one game in the future.

    I do not want to redo the same things over again. If I want multiplayer, I can just grab it from here. If I want a modloader, I can find it here. If I want hotkeys, I can just get it from here. And so on.. That is the motivation behind this project!

    ⚠️ A lot of things showcased here are not on the main branch. Check out the main branch for a working multiplayer scenario and the dev branch for everything else. The main branch is where all the old code is at, dev branch is where all the latest and the greatest is at. Eventually the dev branch will be merged with the main branch.

    Menu
    Quick look at the menus

    Cat with sword
    Attack animation

    2DDungeon
    Dungeon environment

    inv
    Working on a inventory

    eve.mp4

    Attempting to make a FPS

    Modules

    Core

    There is an in-game console (shown by pressing F12) that supports custom commands, useful for in-game testing and debugging.

    image

    There are also popup error and message windows. The bottom right corner of the screen shows a small red box which notifies you of any errors (along with the total error count every second).

    image

    image image image image

    server-and-client-simulated-positions-preview.mp4

    Click here to see an attempt at trying to sync enemy physics with server and client

    Tech Tree

    Tech tree where nodes in tree are positioned automatically via script

    The code for this has not been merged to this repository yet and can be found here

    Contributing

    See CONTRIBUTING.md

    Credit

    Thank you to the following wonderful people who helped make this project become something even greater!

    Programming

    Testers

    Visit original content creator repository https://github.com/CSharpRedotTools/GodotModulesCSharp-Old
  • 🚀 Bot Setup Instructions

    🚀 Bot Setup Instructions

    Welcome to the bot setup guide! Follow the steps below to install and configure the bot correctly. This guide is designed to be beginner-friendly, with clear explanations for each step.


    Table of Contents

    1. Prerequisites
    2. Installation Steps
    3. Configuration Files
    4. Running the Bot
    5. Contact and Support

    Prerequisites

    Before running the bot, make sure you have the following installed:

    • Node.js (Version: 22.11.0)
    • npm (Version: 10.9.0)

    Download Node.js and npm here: Download Link.


    Installation Steps

    1. Download and Extract the Bot Files:

      • Extract the bot package into a folder on your computer.
    2. Install Dependencies:
      Open your terminal or command prompt, navigate to the folder where the bot files are located, and run:

      npm install user-agents axios colors p-limit https-proxy-agent socks-proxy-agent crypto-js ws uuid xlsx readline-sync
    3. Prepare Configuration Files:

      • Ensure all configuration files are set up correctly before running the bot (see Configuration Files section).

    Configuration Files

    1. configs.json – 📜 Adjust Bot Settings

    This file controls the bot’s behavior. Below is an example configuration:

    {
      "timeZone": "en-US",
      "rotateProxy": false,
      "skipInvalidProxy": false,
      "proxyRotationInterval": 2,
      "delayEachAccount": [5, 8],
      "timeToRestartAllAccounts": 300,
      "howManyAccountsRunInOneTime": 100,
      "doTasks": true,
      "playGames": true,
      "referralCode": ""
    }
    • Fields Explained:
      • timeZone: Time zone setting (e.g., “en-US”).
      • rotateProxy: Enable or disable proxy rotation.
      • skipInvalidProxy: Skip invalid proxies if true.
      • proxyRotationInterval: Time interval (in minutes) for rotating proxies.
      • delayEachAccount: Random delay range (in seconds) between accounts.
      • timeToRestartAllAccounts: Time (in seconds) to restart all accounts.
      • howManyAccountsRunInOneTime: Number of accounts to run simultaneously.
      • doTasks: Enable task completion.
      • playGames: Enable game-playing feature.
      • referralCode: Add your referral code (optional). Do not change it if you want to support me ^^

    2. datas.txt – 🗂️ User Data

    Download the datas.txt file from here. This file contains user data in the following format:

    query_id.../user...
    query_id.../user...
    query_id.../user...

    Note: Each row for each account

    3. wallets.txt – 💼 Wallet Addresses

    • Wallets generator: Link

    Add your wallet addresses in the following format:

    • Sui wallet address

    0x...
    0x...
    0x...

    Note: Wallet updates are currently not supported.

    4. proxies.txt – 🌐 Proxy List (Optional)

    If you are using proxies, add them here. Leave the file blank if you are not using proxies. Supported formats:

    http://user:password@host:port
    https://user:password@host:port
    socks4://user:password@host:port
    socks5://user:password@host:port

    Note: each row for each account


    Running the Bot

    1. Navigate to the folder containing the bot files:

      cd /path/to/meomundep-folder
    2. Run the bot using the following command:

      node meomundep

    Contact and Support

    If you encounter any issues or have questions, feel free to reach out:

    Your support is greatly appreciated! 🐱


    Enjoy using the bot! 🚀

    Visit original content creator repository
    https://github.com/MeoMunDep/ZESH-To-The-Moon