npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@webas/ps

v0.1.3

Published

Schema-based model layer and query helper for PostgreSQL.

Downloads

62

Readme

@webas/ps

@webas/ps, PostgreSQL için şema tabanlı model katmanı ve sorgu yardımcısıdır. Amaç; bağlantı havuzu, şema doğrulama, otomatik tablo oluşturma, güvenli sorgu üretimi, hook sistemi ve kolay CRUD işlemlerini tek pakette toplamaktır.

Özellikler

  • PostgreSQL connection pool desteği
  • Şema tanımlama ve alan doğrulama
  • Otomatik _id üretimi
  • Otomatik _v kayıt versiyonu
  • Model ve document yapısı
  • create, save, find, findOne, findById, updateOne, deleteOne
  • JSONB ve array alan desteği
  • Array içindeki object kayıtları için updateArray
  • Soft delete ve timestamps
  • Pre/post hook sistemi
  • Instance ve static method desteği
  • Model tanımlanınca otomatik tablo ve index hazırlığı
  • Transaction ve raw query desteği
  • TypeScript tipleri

Kurulum

npm install @webas/ps pg

Yerel geliştirme için bu repoda:

npm install
npm test

Bağlantı

const { connect } = require("@webas/ps");

await connect({
  host: "localhost",
  port: 5432,
  database: "app",
  user: "postgres",
  password: "password",
  pool: {
    min: 0,
    max: 20
  },
  closeAfterQuery: true
});

Pool varsayılan olarak min: 0, idleTimeoutMillis: 5000, allowExitOnIdle: true, closeAfterQuery: true ve application_name: "@webas/ps" ile çalışır.

closeAfterQuery: true normal sorgularda query bittikten sonra PostgreSQL session'ını idle bırakmaz; client pool'dan alınır, sorgu biter bitmez kapatılır. Pool nesnesi yaşamaya devam eder, bir sonraki sorguda yeni client açılır. Transaction içinde verilen session ise transaction bitene kadar açık kalır ve sonra release edilir.

Yüksek trafikli API sunucusunda klasik pool davranışı istersen:

await connect({
  // ...
  closeAfterQuery: false,
  pool: {
    min: 0,
    max: 20,
    idleTimeoutMillis: 5000
  }
});

Kısa çalışan scriptlerde process kapanırken pool otomatik kapatılır; uzun çalışan uygulamalarda kapanış anında yine de disconnect() çağırmak önerilir.

const { poolStats, disconnect } = require("@webas/ps");

console.log(poolStats()); // { totalCount, idleCount, waitingCount }

await disconnect();

SSL gereken sunucularda:

await connect({
  connectionString: "postgresql://postgres:password@localhost:5432/app",
  ssl: { rejectUnauthorized: false }
});

Şema ve Model

const { Schema, model } = require("@webas/ps");

const UserSchema = new Schema(
  {
    username: {
      type: String,
      required: true,
      unique: true,
      index: true,
      trim: true
    },
    email: {
      type: String,
      required: true,
      lowercase: true
    },
    roles: {
      type: [String],
      default: []
    },
    profile: {
      type: Object,
      jsonb: true,
      default: {}
    },
    tasks: {
      type: [Object],
      default: []
    }
  },
  {
    timestamps: true,
    softDelete: true
  }
);

UserSchema.method("isAdmin", function () {
  return this.roles.includes("admin");
});

UserSchema.virtual("displayName").get(function () {
  return `${this.username} <${this.email}>`;
});

UserSchema.static("findByEmail", function (email) {
  return this.findOne({ email });
});

const User = model("User", UserSchema);

Tablo ve index hazırlığı otomatik yapılır. connect() çağrısından önce tanımlanmış modeller bağlantı kurulunca hazırlanır; bağlantıdan sonra tanımlanan modeller de ilk kullanım öncesi hazırlanır.

Otomatik tablo/index hazırlığı model başına bağlantı süresince bir kez çalışır ve konsolu doldurmaması için loglanmaz. Genel sorgu logları da varsayılan olarak kapalıdır.

Debug için sorgu loglarını bilinçli açmak istersen:

await connect({
  // ...
  debug: true
});

Alternatif:

WEBAS_PS_DEBUG=1 node app.js

CRUD

const user = await User.create({
  username: "professor",
  email: "[email protected]",
  roles: ["admin"]
});

const found = await User.findOne({ username: "professor" });
const byId = await User.findById(user._id);

await User.updateOne(
  { _id: user._id },
  {
    $set: { username: "professor2" },
    $inc: { loginCount: 1 }
  }
);

await User.deleteOne({ _id: user._id });

Soft delete aktifse deleteOne kaydı silmez, deletedAt alanını doldurur.

const deleted = await User.find({}).onlyDeleted();
const withDeleted = await User.find({}).withDeleted();
await User.forceDeleteOne({ _id: user._id });

Kayıt Versiyonu

Her modelde otomatik _v alanı bulunur. Yeni kayıt 0 ile başlar; save, updateOne, updateMany, updateArray, pushArray, pullArray ve soft delete gibi update üreten işlemlerde otomatik +1 artar.

const user = await User.create({
  username: "professor",
  email: "[email protected]"
});

console.log(user._v); // 0

await User.updateOne(
  { _id: user._id },
  { $set: { username: "professor2" } }
);

const updated = await User.findById(user._id);
console.log(updated._v); // 1

_v alanı iç sayaçtır; update sırasında manuel _v değeri verilirse yok sayılır ve sayaç yine otomatik artırılır.

Query Builder

const users = await User.find({ isActive: true })
  .select("_id username email")
  .sort("-createdAt")
  .limit(20)
  .skip(0)
  .lean();

Index Sistemi

Model tanımlandığında tablo ve index komutları otomatik hazırlanır. Alan üzerinde index: true veya unique: true kullanabilirsin.

const UserSchema = new Schema({
  username: {
    type: String,
    index: true
  },
  email: {
    type: String,
    unique: true
  },
  createdAt: {
    type: Date,
    index: true
  }
});

Composite, partial ve GIN index:

UserSchema.index({ username: 1, createdAt: -1 });
UserSchema.index({ email: 1 }, { unique: true, where: { deletedAt: null } });
UserSchema.index({ profile: "gin" }, { type: "gin" });

Bu tanımlar CREATE INDEX IF NOT EXISTS, CREATE UNIQUE INDEX IF NOT EXISTS ve USING GIN olarak veritabanına uygulanır. Sık kullanılan filtre ve sıralama alanlarında index tanımlamak okuma hızını ciddi şekilde artırır.

Cursor tabanlı sayfalama:

const users = await User.find({ isActive: true })
  .sort({ _id: -1 })
  .cursor({
    after: "322031828070350848",
    limit: 50
  });

Sayfa tabanlı kullanım:

const page = await User.paginate(
  { isActive: true },
  {
    page: 1,
    limit: 25,
    sort: { _id: -1 }
  }
);

Filtre operatorleri:

const users = await User.find({
  age: { $gte: 18, $lte: 65 },
  role: { $in: ["admin", "moderator"] },
  $or: [{ username: "Ali" }, { username: "Veli" }]
});

Update ve Delete Kısayolları

const updated = await User.findByIdAndUpdate(
  user._id,
  { age: 25 },
  { new: true }
);

// Object filter de kabul edilir. Kayıt yoksa new/upsert ile oluşturulur.
const stat = await Stat.findByIdAndUpdate(
  { _id: statId },
  { $inc: { count: 1 } },
  { new: true }
);

const updatedOne = await User.findOneAndUpdate(
  { email: "[email protected]" },
  { $set: { role: "admin" } },
  { new: true, lean: true }
);

const deleted = await User.findByIdAndDelete(user._id);
const deletedOne = await User.findOneAndDelete({ email: "[email protected]" });

Sayma ve Toplu İşlemler

const count = await User.countDocuments({ role: "admin" });
const estimated = await User.estimatedDocumentCount();
const exists = await User.exists({ email: "[email protected]" });
const roles = await User.distinct("role", { isActive: true });

bulkWrite:

await User.bulkWrite([
  {
    insertOne: {
      document: { username: "Ali", email: "[email protected]" }
    }
  },
  {
    updateOne: {
      filter: { email: "[email protected]" },
      update: { $set: { role: "admin" } }
    }
  },
  {
    deleteMany: {
      filter: { isActive: false }
    }
  }
]);

Array Güncelleme

updateArray, JSONB array alanlarında object bulma, düzenleme, silme ve yeni eleman ekleme için kullanılır.

await User.updateArray(
  { _id: user._id },
  "tasks",
  {
    match: { id: "todo-1" },
    $set: {
      done: true,
      "meta.finishedBy": "worker-1"
    },
    $inc: {
      priority: 2
    }
  }
);

Birden fazla elemanı güncellemek:

await User.updateArray(
  { _id: user._id },
  "tasks",
  {
    match: { done: false },
    multiple: true,
    $set: { archived: true }
  }
);

Eleman eklemek:

await User.pushArray(
  { _id: user._id },
  "tasks",
  { id: "todo-3", title: "Ship release", done: false }
);

Aynı eleman yoksa eklemek:

await User.updateArray(
  { _id: user._id },
  "tasks",
  {
    $addToSet: { id: "todo-3", title: "Ship release", done: false }
  }
);

Object silmek:

await User.updateArray(
  { _id: user._id },
  "tasks",
  {
    match: { id: "todo-2" },
    remove: true
  }
);

Pull işlemi:

await User.pullArray({ _id: user._id }, "tasks", { done: false });

Eşleşme yoksa eklemek:

await User.updateArray(
  { _id: user._id },
  "tasks",
  {
    match: { id: "todo-4" },
    upsert: { id: "todo-4", title: "Created by upsert" },
    $set: { done: false }
  }
);

Hook Kullanımı

UserSchema.pre("save", function () {
  this.updatedAt = new Date();
});

UserSchema.post("save", function (doc) {
  console.log("saved:", doc._id);
});

Transaction

const { transaction } = require("@webas/ps");

await transaction(async (session) => {
  const user = await User.create(
    { username: "professor", email: "[email protected]" },
    { session }
  );

  await Wallet.create(
    { user: user._id, balance: 0 },
    { session }
  );
});

Raw Query

const { raw } = require("@webas/ps");

const result = await raw(
  "SELECT * FROM users WHERE username = $1",
  ["professor"]
);

Test

Ana dizindeki örnek dosyayı çalıştır:

node test.js

Paket testleri:

npm test
npm run lint

Public API

const {
  connect,
  disconnect,
  Schema,
  model,
  transaction,
  createId,
  raw
} = require("@webas/ps");

Lisans

MIT