Skip to content
Projetos

Sobre

Uma nova forma de criar servidores web e modelos de dados NoSQL

Sistemas e infraestrutura

Como estes números são medidos

Crescimento medido de estrelas

em 24 h
0
em 7 dias
0
em 15 dias
0
em 1 mês
Coletando histórico

Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.

README.md

Original

🇮🇷 Iran · 🇵🇸 Palestine · Hezbollah 🇱🇧
We support the axis of resistance — Iran, Palestine, Hezbollah in Lebanon, and all those
who stand against the decades of suffering and crimes inflicted on the people of our region.

بسم الله الرحمن الرحیم

Lesan logo

The New Way to Build Web Servers

GraphQL-like flexibility with unmatched performance.
Client-driven projections, automatic relationships, end-to-end TypeScript safety.

npm version JSR version License: AGPL-3.0 Node.js, Bun, Deno TypeScript

Documentation · Getting Started · Benchmarks · Examples


Why Lesan?

Lesan is a blazing-fast, cross-platform web framework and Object Document Mapper (ODM) designed to give you the exact data-fetching flexibility of GraphQL — without its heavy processing overhead — while maintaining the simplicity of REST.

Even though NoSQL is very fast, its complexities become troublesome in large-scale projects. On the other hand, GraphQL shines in client-server connectivity but adds another layer of complexity and CPU cost. That's why we created Lesan: the flexibility of GraphQL, the simplicity of REST, and the raw speed of direct MongoDB queries.

🚀 Now Cross-Platform! Write your code once and run it natively on Node.js, Bun, and Deno — zero configuration required.

✨ What makes Lesan special?

  • 🎯 Client-Driven Projections — Clients dictate exactly the shape and depth of the data they receive, including nested relations, without the CPU cost of parsing a complex query language.
  • 🤝 One-Directional Magic, Bi-Directional Power — Define a relationship from one direction, and Lesan automatically handles the complex bi-directional embedding, syncing, array limits, sorting, and cascading updates/deletes behind the scenes. Goodbye to complex JOINs and manual NoSQL array updates.
  • 🛡️ End-to-End Type Safety — Run your server with typeGeneration: true, and Lesan auto-generates perfect client-side TypeScript definitions and a custom fetch wrapper for flawless frontend integration and autocomplete.
  • ⚡ Insane Performance — Stripped of middleware bloat and built directly on the official MongoDB driver, Lesan's direct-to-database routing crushes traditional REST/ORM and GraphQL server speeds.
  • 🧩 Built for Microservices — The action-based architecture inherently supports breaking large monolithic systems down into isolated microservices.
  • 🍃 MongoDB Native — Full compatibility with MongoDB's powerful query language.

Installation

Lesan is designed to work seamlessly across all major JavaScript runtimes.

Node.js

npm install @hemedani/lesan mongodb

Bun

bun add @hemedani/lesan mongodb

Deno

import { lesan } from "jsr:@hemedani/lesan";
import { MongoClient } from "npm:mongodb";

A little trip

Look at the code below:

Create a file called main.ts (or main.js) and paste the code below into it.

This single file is a complete, runnable Lesan server. It is built from three parts that mirror the mental model of the whole framework:

  1. Model Section — we describe our data shapes (country and user) as MongoDB collections using superstruct validators. Each model may also declare relations — here, every user belongs to one country, and each country automatically keeps a sorted, limited list of its users.
  2. Functions Section — we define acts (routes). Each act has a validator (what input the client must send, and which fields the client may ask to receive back) and an fn (the actual database work). Acts are registered with coreApp.acts.setAct and are called by name from the client.
  3. Run Section — we start the HTTP server. The client never builds URLs by hand; it just sends { service, model, act, details } to /lesan.

A Lesan request is nothing but a JSON object like this: { "service": "main", "model": "country", "act": "addCountry", "details": { "set": {...}, "get": {...} } } The set is the input data, and the get is the projection — exactly which fields (and how deeply) you want back.

📦 Click to expand the full commented example
// ============================================================
// 1. IMPORTS — everything you need comes from a single package
// ============================================================
import {
  ActFn,     // Type helper for an act handler: (body) => Promise<any>
  Document,  // MongoDB document type, used for building filters
  Filter,    // MongoDB filter type (the `where` clause of the query)
  lesan,     // The framework factory — creates your whole app
  number,    // superstruct validator: a number field
  object,    // superstruct validator: an object of fields
  ObjectId,  // MongoDB ObjectId, used to link documents together
  optional,  // superstruct wrapper: the field may be missing
  size,      // superstruct validator: enforces a string length (e.g. 24)
  string,    // superstruct validator: a string field
} from "@hemedani/lesan"; // Use "jsr:@hemedani/lesan" for Deno
import { MongoClient } from "mongodb"; // Use "npm:mongodb" for Deno

// ============================================================
// 2. APP + DATABASE — one app object, one MongoDB database
// ============================================================

// lesan() returns an object holding schemas, acts, odm and runServer.
// Everything is wired together through closures — no global state.
const coreApp = lesan();

// Connect to MongoDB (make sure a local mongod is running on 27017).
const client = await new MongoClient("mongodb://127.0.0.1:27017/").connect();
const db = client.db("civil"); // we'll use the "civil" database

// Hand the database to the ODM — all models will use it from now on.
coreApp.odm.setDb(db);

// ============================================================
// 3. MODEL SECTION — describe your data shapes + relations
// ============================================================

// -------- Country model --------
// Each model has a "pure" set of fields, described with superstruct.
const countryPure = {
  name: string(),
  population: number(),
  abb: string(),
};
// Country has no relations of its own (for now).
const countryRelations = {};
// Register the model. `newModel` computes relations and returns an
// ODM object with methods: insertOne, find, updateOne, deleteOne, ...
const countries = coreApp.odm.newModel("country", countryPure, countryRelations);

// -------- User model --------
const userPure = {
  name: string(),
  age: number(),
};

// The user model declares ONE relation: `country` (single — one country).
const users = coreApp.odm.newModel("user", userPure, {
  country: {
    optional: false,            // every user MUST have a country
    schemaName: "country",      // the related model's name
    type: "single",             // single = one-to-one/one-to-many; "multiple" = many-to-many
    relatedRelations: {
      // The reverse side, defined automatically on the Country model:
      users: {
        type: "multiple",       // a country can have many users
        limit: 50,              // keep at most 50 back-references embedded
        sort: {
          field: "_id",         // newest first
          order: "desc",
        },
      },
    },
  },
});

// ============================================================
// 4. FUNCTIONS SECTION — acts = routes = API endpoints
// ============================================================

// Each act needs a validator: what the client may send (`set`) and
// what it may ask to receive (`get`). Superstruct validates at runtime,
// so bad requests never reach your handler.

// ---------- Add Country ----------
const addCountryValidator = () => {
  return object({
    set: object(countryPure),                             // input: name/population/abb
    get: coreApp.schemas.selectStruct("country", { users: 1 }), // output: country fields + 1 level of users
  });
};

const addCountry: ActFn = async (body) => {
  // `body.details.set` is the validated input the client sent.
  const { name, population, abb } = body.details.set;
  // Insert one document; `projection` controls which fields are returned.
  return await countries.insertOne({
    doc: { name, population, abb },
    projection: body.details.get,
  });
};

// Register the act under the "country" model with the name "addCountry".
coreApp.acts.setAct({
  schema: "country",
  actName: "addCountry",
  validator: addCountryValidator(),
  fn: addCountry,
});

// ---------- Get Countries (paged) ----------
const getCountriesValidator = () => {
  return object({
    set: object({
      page: number(),
      limit: number(),
    }),
    get: coreApp.schemas.selectStruct("country", 1), // only country's own fields
  });
};

const getCountries: ActFn = async (body) => {
  let {
    set: { page, limit },
    get,
  } = body.details;

  // Sensible defaults for pagination.
  page = page || 1;
  limit = limit || 50;
  const skip = limit * (page - 1);

  // A plain MongoDB query — no query language, just chained driver calls.
  return await countries.find({ projection: get, filters: {} }).skip(skip).limit(limit).toArray();
};

coreApp.acts.setAct({
  schema: "country",
  actName: "getCountries",
  validator: getCountriesValidator(),
  fn: getCountries,
});

// ---------- Add User (with its Country relation) ----------
const addUserValidator = () => {
  return object({
    set: object({
      ...userPure,
      country: string(), // client sends the country `_id` as a 24-char string
    }),
    get: coreApp.schemas.selectStruct("user", 1),
  });
};
const addUser: ActFn = async (body) => {
  const { country, name, age } = body.details.set;

  // Insert the user AND wire up the relation in one step.
  return await users.insertOne({
    doc: { name, age },
    projection: body.details.get,
    relations: {
      country: {
        _ids: new ObjectId(country), // link to the chosen country
        relatedRelations: {
          users: true, // also embed this user back into the country's `users`
        },
      },
    },
  });
};

coreApp.acts.setAct({
  schema: "user",
  actName: "addUser",
  validator: addUserValidator(),
  fn: addUser,
});

// ---------- Get Users (optionally filtered by country) ----------
const getUsersValidator = () => {
  return object({
    set: object({
      page: number(),
      limit: number(),
      countryId: optional(size(string(), 24)), // optional 24-char ObjectId string
    }),
    get: coreApp.schemas.selectStruct("user", { country: 1 }), // include embedded country
  });
};
const getUsers: ActFn = async (body) => {
  let {
    set: { page, limit, countryId },
    get,
  } = body.details;

  page = page || 1;
  limit = limit || 50;
  const skip = limit * (page - 1);

  // Build the MongoDB filter. Because relations are embedded, we can
  // filter on `country._id` directly — no JOIN required.
  const filters: Filter<Document> = {};
  countryId && (filters["country._id"] = new ObjectId(countryId));

  return await users.find({ projection: get, filters }).skip(skip).limit(limit).toArray();
};

coreApp.acts.setAct({
  schema: "user",
  actName: "getUsers",
  validator: getUsersValidator(),
  fn: getUsers,
});

// ============================================================
// 5. RUN SECTION — start the server
// ============================================================

// Start listening on port 1366.
//  - playground: true  → serve the interactive explorer at /playground
//  - typeGeneration: true → auto-generate client-side TypeScript types
coreApp.runServer({ port: 1366, typeGeneration: false, playground: true });

⚡ Tip: The code above is only ~150 lines, yet it gives you four full API endpoints (addCountry, getCountries, addUser, getUsers) with pagination, filtering, and automatic bi-directional relation syncing. Try changing the get projection in a request to see how the returned shape changes — with zero backend changes.

Run the server

Depending on your runtime, run the following command in your terminal:

Node.js (requires tsx or similar for TypeScript):

npx tsx main.ts

Bun:

bun run main.ts

Deno:

deno run -A main.ts

You should see this message:

HTTP webserver running.
please send a post request to http://localhost:1366/lesan
you can visit playground on http://localhost:1366/playground

Listening on http://localhost:1366/

Now you can visit the playground at http://localhost:1366/playground and send requests to the server for addCountry, addUser, and getUsers. Screen Shot 1402-04-26 at 20 47 05

Alternatively, you can send a POST request to http://localhost:1366/lesan with postman including the following in JSON format inside the body in order to retrieve the desired data:

{
  "service": "main",
  "model": "country",
  "act": "addCountry",
  "details": {
    "set": {
      "name": "Iran",
      "population": 85000000,
      "abb": "IR"
    },
    "get": {
      "_id": 1,
      "name": 1,
      "population": 1,
      "abb": 1
    }
  }
}

Screen Shot 1402-04-25 at 18 24 16

The Magic of Lesan Relationships ✨

In Lesan, relationships are One-Directional in definition, but fully embedded bi-directionally. When you link a User to a Country, Lesan seamlessly embeds the country details inside the user, and automatically embeds the user details inside the country's users array (even keeping the top 50 users sorted automatically!).

We handle all the heavy lifting of keeping this embedded data perfectly in sync across your entire database for blazing-fast reads. You can also control the exact level of penetration into the relationship depth. On the client-side, you simply describe what you want and get back exactly what you described — with zero backend refactoring!

Benchmarks

benchmark-animation

We use this formula to calculate the difference: (B - A) ÷ A × 100 As you see on the chart:

  • Lesan return data to client 1168% faster than the prisma-express-rest. Which uses postgres as a database.
  • Lesan return data to client 1417% faster than the prisma-express-graphql. Which uses postgres as a database.
  • Lesan return data to client 4435% faster than the mongoose-express-rest (Note that we did not sort in this query)
  • Lesan return data to client 72289% faster than the mongo-express-rest (Note that we did not sort in this query)
  • Lesan return data to client 298971% faster than the mongoose-express-rest (used sortby)

Maybe we created the most performant framework in the world! see more detailed benchmark

Note: With our new cross-platform architecture, Lesan achieves over 10,000 requests per second on Bun and Deno! Check out our Cross-Platform Benchmarks.

Documentation

This video is an introductory tutorial on the Lesan framework in the Farsi language.

Contributors

Many thanks to those who supported us

Mehrshad Cheshm Khavari
Mehrshad Cheshm Khavari
Mahdi Ramezani
Mahdi Ramezani
Alireza Safaierad
Alireza Safaierad
ali davodi
ali davodi
sorena ganji
sorena ganji
Node Master
Node Master
Alireza Safaierad
Alireza Safaierad
Erfan Asadi
Erfan Asadi

Licensed under the AGPL-3.0-or-later license. Built with ❤️ by the Lesan team.

Explore projetos relacionados

Carregando…