Altbilgi içeriğine atla
NODE YARDıM

Hashids NPM (Geliştiriciler İçin Nasıl Çalışır)

Modern web uygulamalarında veri güvenliği ve mahremiyetini sağlamak önemlidir. Veritabanı kimlikleri veya URL'ler gibi hassas bilgileri korumanın bir yolu, sayısal verileri benzersiz, tersine çevrilebilir ve şifreli hash'lere dönüştüren bir JavaScript şifreleme kütüphanesi olan Hashids kullanmaktır. Bu makale, Hashids'i React uygulamanıza sorunsuz bir şekilde entegre edip tanımlayıcıları gizleme ve decode etme yollarını inceler.

Hashids nedir?

Hashids, sayısal verileri hash dizesine dönüştüren küçük ama güçlü bir kütüphanedir. Birincil hedef, hassas bilgilerin açığa çıkmasını önlemek için sayısal tanımlayıcıları gizlemektir. Bu dönüşüm tersine çevrilebilir, gerektiğinde orijinal sayısal verinin geri alınmasına olanak tanır. Hashids, sayılardan YouTube benzeri kimlikler oluşturmak, hassas verileri kodlamak veya kullanıcılarınıza veritabanı kimliklerinizi güvenli bir şekilde göstermek ya da sadece kimlikleri sayılardan gizlemek için kullanılan bir JavaScript kütüphanesidir.

React Uygulamanıza Hashids'i Entegre Etmek

Hashids'i React uygulamanıza entegre etmek için şu adımları izleyin:

Adım 1: Hashids npm'i yükleyin

Öncelikle, React projenize npm üzerinden Hashids yükleyin:

npm install hashids
# or
yarn add hashids
npm install hashids
# or
yarn add hashids
SHELL

Adım 2: Hashids Örneği Başlatın

React bileşeninizde veya yardımcı dosyanızda tuzla ve isteğe bağlı olarak minimum hash uzunluğu ile yeni bir Hashids örneğini başlatın:

import { useState, useEffect } from 'react';
import Hashids from 'hashids';

// React component demonstrating Hashids integration
const MyComponent = () => {
  const [hashids, setHashids] = useState(null);

  useEffect(() => {
    // Initialize the Hashids library with a custom salt string and minimum hash length of 8
    const initHashids = new Hashids('your_salt_here', 8); // Replace 'your_salt_here' with your actual salt or configure custom alphabet
    setHashids(initHashids);
  }, []);

  // Other component logic here
  return (
    <div>
      {/* Your JSX content */}
    </div>
  );
};

export default MyComponent;
import { useState, useEffect } from 'react';
import Hashids from 'hashids';

// React component demonstrating Hashids integration
const MyComponent = () => {
  const [hashids, setHashids] = useState(null);

  useEffect(() => {
    // Initialize the Hashids library with a custom salt string and minimum hash length of 8
    const initHashids = new Hashids('your_salt_here', 8); // Replace 'your_salt_here' with your actual salt or configure custom alphabet
    setHashids(initHashids);
  }, []);

  // Other component logic here
  return (
    <div>
      {/* Your JSX content */}
    </div>
  );
};

export default MyComponent;
JAVASCRIPT

Hash çıktısını özelleştirmek için kullandığınız benzersiz bir dize (tuz) ile 'your_salt_here' öğesini değiştirin.

Adım 3: Verileri Kodlama ve Kod çözme

Başlatıldıktan sonra, sayısal verileri kodlamak ve kodunu çözmek için Hashids'i kullanabilirsiniz. Örneğin, bir veritabanı kimliğini kodlamak:

const encodedId = hashids.encode(12345); // Example: 'B0zGbvA9' non-sequential IDs
const encodedId = hashids.encode(12345); // Example: 'B0zGbvA9' non-sequential IDs
JAVASCRIPT

Ve orijinal kimliğine geri kod çözmek:

const decodedIds = hashids.decode('B0zGbvA9'); // Example: [12345]
const decodedIds = hashids.decode('B0zGbvA9'); // Example: [12345]
JAVASCRIPT

Adım 4: Bileşenlerde Hashids'i Kullanma

Gerekli yerlerde React bileşenlerinizin içinde Hashids'i entegre edin. Örneğin, hashlenmiş kimlikleri prop olarak geçirme:

const MyComponent = ({ id }) => {
  // Encode ID using Hashids if the hashids instance is initialized
  const encodedId = hashids ? hashids.encode(id) : '';

  return (
    <div>
      <p>Encoded ID: {encodedId}</p>
      {/* Other JSX content */}
    </div>
  );
};
const MyComponent = ({ id }) => {
  // Encode ID using Hashids if the hashids instance is initialized
  const encodedId = hashids ? hashids.encode(id) : '';

  return (
    <div>
      <p>Encoded ID: {encodedId}</p>
      {/* Other JSX content */}
    </div>
  );
};
JAVASCRIPT

React'te Hashids Kullanmanın Yararları

  • Güvenlik: Hashids, sayısal kimlikleri gizleyerek veri gizliliğini ve güvenliğini artırır, hassas bilgilere doğrudan erişimi engeller.
  • Entegrasyon Kolaylığı: Basit npm kurulumu ve kolay API, Hashids'in React uygulamalarında uygulanmasını kolaylaştırır.
  • Esneklik: Özelleştirilebilir hash uzunluğu ve tuz, uygulamanızın güvenlik ihtiyaçlarına göre hash'leri uyarlama esnekliği sağlar.

IronPDF'i Tanıtma

IronPDF for Node.js Iron Software'dan gelen güçlü bir Node.js PDF kütüphanesidir ve .NET projelerinde PDF oluşturup düzenlemenize olanak tanır. HTML'den PDF oluşturmanız, mevcut PDF'leri değiştirmeniz veya web sayfalarını PDF formatına dönüştürmeniz gerektiğinde, IronPDF ihtiyaçınızı karşılar.

Hashids NPM (Geliştiriciler İçin Nasıl Çalışır): Şekil 1 - IronPDF for Node.js: Node.js PDF Kütüphanesi

Ana Özellikler

HTML'den PDF'ye Dönüşüm

HTML içeriğini kolayca PDF belgelerine dönüştürün. Bu özellik, web içeriğinden dinamik PDF'ler üretmek için özellikle kullanışlıdır.

URL'den PDF'ye Dönüşüm

Web sayfalarının içeriğini yakalayıp programatik olarak PDF dosyaları olarak kaydedebilmeniz için URL'lerden doğrudan PDF oluşturun.

PDF Manipülasyonu

Mevcut PDF belgelerini kolayca birleştirin, ayırın ve yönetin. IronPDF, sayfa ekleme, belge ayırma gibi işlevler sunar.

PDF Güvenliği

PDF belgelerinizi şifrelerle şifreleyerek veya dijital imzalar uygulayarak güvence altına alın. IronPDF, hassas belgelerinizi yetkisiz erişimden korumak için seçenekler sunar.

Yüksek Kaliteli Çıktı

Metin, resim ve biçimlendirmenin hassas bir şekilde işlendiği yüksek kaliteli PDF belgeleri üretin. IronPDF, oluşturulan PDF'lerin orijinal içeriği korumasını sağlar.

Çapraz Platform Uyumluluğu

IronPDF, Windows, Linux ve macOS dahil olmak üzere çeşitli platformlarla uyumludur, bu da onu geniş bir geliştirme ortamı yelpazesi için uygun hale getirir.

Basit Entegrasyon

IronPDF'i npm paketi ile Node.js uygulamalarınıza kolayca entegre edin. API iyi belgelenmiştir, bu da projelerinize PDF oluşturma yeteneklerini kolayca eklemenizi sağlar.

Kurulum

IronPDF NPM paketini yüklemek için aşağıdaki komutu kullanın:

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
SHELL

IronPDF Kullanarak PDF Belgeleri Oluşturun ve HashIDs NPM Paketini Kullanın

Bağımlılıkları Yükleme: Öncelikle, yeni bir Next.js projesi oluşturun (henüz yapmadıysanız) ve şu komutu kullanarak: buraya bakın

npx create-next-app@latest hashids-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
npx create-next-app@latest hashids-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
SHELL

Sonra, proje dizininize gidin:

cd hashids-pdf
cd hashids-pdf
SHELL

Gerekli paketleri yükleyin:

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add hashids
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add hashids
SHELL

Bir PDF Oluşturun

Şimdi, IronPDF kullanarak PDF oluşturmanın basit bir örneğini oluşturalım. Next.js bileşeninizde (örneğin, pages/index.tsx) aşağıdaki kodu ekleyin:

PDF Oluşturma API'sı: İlk adım PDF belgesini oluşturmak için bir backend API oluşturmak. IronPDF yalnızca sunucu tarafında çalıştığı için, bir kullanıcının PDF oluşturmak istediğinde çağırabileceği bir API oluşturmamız gerekiyor. Aşağıdaki içeriği ekleyerek pages/api/pdf.js yolunda bir dosya oluşturun.

IronPDF bir lisans anahtarı gerektirir, bunu lisans sayfasından alabilir ve aşağıdaki koda yerleştirebilirsiniz.

// pages/api/pdf.js
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
import Hashids from 'hashids';

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";

export default async function handler(req, res) {
  try {
    const initHashids = new Hashids('IronPDF Is Awesome and this is the salt', 8);
    const f = req.query.f;
    const l = initHashids.encode(f);

    let content = "<h1>Demo Hashids and Generate PDF Using IronPDF</h1>";
    content += "<p>Input:" + f + "</p>";
    content += "<p>HashID:" + l + "</p>";

    const pdf = await PdfDocument.fromHtml(content);
    const data = await pdf.saveAsBuffer();

    res.setHeader("Content-Type", "application/pdf");
    res.setHeader(
      "Content-Disposition",
      "attachment; filename=awesomeIron.pdf"
    );
    res.send(data);
  } catch (error) {
    console.error("Error generating PDF:", error);
    res.status(500).end();
  }
}
// pages/api/pdf.js
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
import Hashids from 'hashids';

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";

export default async function handler(req, res) {
  try {
    const initHashids = new Hashids('IronPDF Is Awesome and this is the salt', 8);
    const f = req.query.f;
    const l = initHashids.encode(f);

    let content = "<h1>Demo Hashids and Generate PDF Using IronPDF</h1>";
    content += "<p>Input:" + f + "</p>";
    content += "<p>HashID:" + l + "</p>";

    const pdf = await PdfDocument.fromHtml(content);
    const data = await pdf.saveAsBuffer();

    res.setHeader("Content-Type", "application/pdf");
    res.setHeader(
      "Content-Disposition",
      "attachment; filename=awesomeIron.pdf"
    );
    res.send(data);
  } catch (error) {
    console.error("Error generating PDF:", error);
    res.status(500).end();
  }
}
JAVASCRIPT

hashID ve IronPDF kullanmak için index.js kodunu aşağıdaki gibi değiştirin.

import Head from "next/head";
import styles from "../styles/Home.module.css";
import React, { useState, useEffect } from "react";
import Hashids from 'hashids';

export default function Home() {
  const [text, setText] = useState("");
  const [etext, seteText] = useState("");
  const [hashids, setHashids] = useState(null);

  // Initialize Hashids on component mount
  useEffect(() => {
    const initHashids = new Hashids('IronPDF Is Awesome and this is the salt', 8);
    setHashids(initHashids);
  }, []);

  // Generate PDF by calling backend API
  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf?f=" + text);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (error) {
      console.error("Error generating PDF:", error);
    }
  };  

  // Handle text change and encode input number
  const handleChange = (event) => {
    seteText(hashids ? hashids.encode(event.target.value) : '');
    setText(event.target.value);
  };

  return (
    <div className={styles.container}>
      <Head>
        <title>Generate PDF Using IronPDF</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <h1>Demo Hashids and Generate PDF Using IronPDF</h1>
        <p>
          <span>Enter Url To get Hashids and Convert to PDF:</span>{" "}
        </p>
        <input type="number" value={text} onChange={handleChange} />
        <p>
          HashID of input: {etext}
        </p>        
        <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>
          Generate PDF 
        </button>
      </main>
      <style jsx>{`
        main {
          padding: 5rem 0;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
        footer {
          width: 100%;
          height: 100px;
          border-top: 1px solid #eaeaea;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        footer img {
          margin-left: 0.5rem;
        }
        footer a {
          display: flex;
          justify-content: center;
          align-items: center;
          text-decoration: none;
          color: inherit;
        }
        code {
          background: #fafafa;
          border-radius: 5px;
          padding: 0.75rem;
          font-size: 1.1rem;
          font-family:
            Menlo,
            Monaco,
            Lucida Console,
            Liberation Mono,
            DejaVu Sans Mono,
            Bitstream Vera Sans Mono,
            Courier New,
            monospace;
        }
      `}</style>
      <style jsx global>{`
        html,
        body {
          padding: 0;
          margin: 0;
          font-family:
            -apple-system,
            BlinkMacSystemFont,
            Segoe UI,
            Roboto,
            Oxygen,
            Ubuntu,
            Cantarell,
            Fira Sans,
            Droid Sans,
            Helvetica Neue,
            sans-serif;
        }
        * {
          box-sizing: border-box;
        }
      `}</style>
    </div>
  );
}
import Head from "next/head";
import styles from "../styles/Home.module.css";
import React, { useState, useEffect } from "react";
import Hashids from 'hashids';

export default function Home() {
  const [text, setText] = useState("");
  const [etext, seteText] = useState("");
  const [hashids, setHashids] = useState(null);

  // Initialize Hashids on component mount
  useEffect(() => {
    const initHashids = new Hashids('IronPDF Is Awesome and this is the salt', 8);
    setHashids(initHashids);
  }, []);

  // Generate PDF by calling backend API
  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf?f=" + text);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (error) {
      console.error("Error generating PDF:", error);
    }
  };  

  // Handle text change and encode input number
  const handleChange = (event) => {
    seteText(hashids ? hashids.encode(event.target.value) : '');
    setText(event.target.value);
  };

  return (
    <div className={styles.container}>
      <Head>
        <title>Generate PDF Using IronPDF</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <h1>Demo Hashids and Generate PDF Using IronPDF</h1>
        <p>
          <span>Enter Url To get Hashids and Convert to PDF:</span>{" "}
        </p>
        <input type="number" value={text} onChange={handleChange} />
        <p>
          HashID of input: {etext}
        </p>        
        <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>
          Generate PDF 
        </button>
      </main>
      <style jsx>{`
        main {
          padding: 5rem 0;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
        footer {
          width: 100%;
          height: 100px;
          border-top: 1px solid #eaeaea;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        footer img {
          margin-left: 0.5rem;
        }
        footer a {
          display: flex;
          justify-content: center;
          align-items: center;
          text-decoration: none;
          color: inherit;
        }
        code {
          background: #fafafa;
          border-radius: 5px;
          padding: 0.75rem;
          font-size: 1.1rem;
          font-family:
            Menlo,
            Monaco,
            Lucida Console,
            Liberation Mono,
            DejaVu Sans Mono,
            Bitstream Vera Sans Mono,
            Courier New,
            monospace;
        }
      `}</style>
      <style jsx global>{`
        html,
        body {
          padding: 0;
          margin: 0;
          font-family:
            -apple-system,
            BlinkMacSystemFont,
            Segoe UI,
            Roboto,
            Oxygen,
            Ubuntu,
            Cantarell,
            Fira Sans,
            Droid Sans,
            Helvetica Neue,
            sans-serif;
        }
        * {
          box-sizing: border-box;
        }
      `}</style>
    </div>
  );
}
JAVASCRIPT

Kod Açıklaması

  1. Kullanıcı, giriş metin kutusu aracılığıyla giriş sayıları girer.
  2. Giriş numarası HashID kullanılarak kodlanır ve görüntülenir.
  3. Kullanıcı 'PDF Oluştur' düğmesine tıkladığında, giriş metni kodlamak ve PDF belgesi oluşturmak için arka uç API'ye gönderilir.

Çıktı

Hashids NPM (Geliştiriciler İçin Nasıl Çalışır): Şekil 2

PDF

Hashids NPM (Geliştiriciler İçin Nasıl Çalışır): Şekil 3

IronPDF Lisansı

IronPDF.

Lisans Anahtarını buraya yerleştirin:

import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
JAVASCRIPT

Sonuç

Hashids'i React uygulamanıza entegre etmek, veri tabanı kimlikleri veya URL'ler gibi hassas verileri korumanın pratik bir yoludur. Hashids'i kullanarak kimliklerin güvenli kalmasını sağlarken, gerektiğinde orijinal verileri geri yükleme yeteneğini koruyabilirsiniz.

Küçük bir uygulama mı yoksa karmaşık bir kurumsal sistem mi inşa ediyorsunuz, Hashids, React projelerinizde veri gizliliğini ve güvenliğini artırmak için güvenilir bir çözüm sunar ve artış gösteren sayıları benzersiz hash'lara kodlama konusunda mükemmeldir. Hashids, giriş numaralarındaki tekrar eden desenlerin bile farklı, tekrar etmeyen hash'lar üretmesini sağlar, uygulamalarda veri bütünlüğünü ve güvenliğini korur.

IronPDF, kapsamlı PDF oluşturma, manipülasyon ve yönetim yetenekleri arayan Node.js geliştiricileri için sağlam ve çok yönlü bir kütüphane olarak öne çıkmaktadır. Web uygulamaları, masaüstü yazılımları veya kurumsal çözümlere PDF işlevselliği entegre edip etmediğinize bakılmaksızın.

Darrius Serrant
Tam Yığın Yazılım Mühendisi (WebOps)

Darrius Serrant, Miami Üniversitesi'nden Bilgisayar Bilimleri lisans derecesine sahiptir ve Iron Software'de Tam Yığın WebOps Pazarlama Mühendisi olarak çalışmaktadır. Küçük yaşlardan itibaren kodlamaya ilgi duyan Darrius, bilişimi hem gizemli hem de erişilebilir buldu ve onu yaratıcılık ve problem çö...

Daha Fazlasını Oku

Iron Destek Ekibi

Haftanın 5 günü, 24 saat çevrimiçiyiz.
Sohbet
E-posta
Beni Ara