Monday, July 1, 2024

Giả lập một API sử dụng Json Server

-

Json-server là một công cụ đơn giản mà mạnh mẽ, được viết bằng Node.js, cho phép bạn tạo một REST API giả mạo nhanh chóng dựa trên một file JSON.

Các tính năng chính của json-server bao gồm:

  • Tạo một REST API đầy đủ từ một file Json đơn giản.
  • Hỗ trợ các phương thức HTTP chuẩn như GET, POST, PUT, PATCH, và DELETE.
  • Hỗ trợ lọc, phân trang và sắp xếp dữ liệu.
  • Tự động tạo các tài nguyên lồng nhau dựa trên cấu trúc của file JSON.
  • Cung cấp một giao diện người dùng dựa trên trình duyệt để xem và thao tác với dữ liệu.

json-server rất hữu ích khi bạn cần một backend giả mạo để phát triển frontend, thử nghiệm hoặc mô phỏng các tình huống khác nhau.

json-server không có trong kho lưu trữ chính thức của Ubuntu, vì vậy bạn không thể cài đặt nó bằng apt. Thay vào đó, bạn cần cài đặt nó thông qua npm, trình quản lý gói của Node.js.

Đầu tiên, cài đặt Node.js và npm. Trên Ubuntu, bạn có thể làm điều này bằng cách chạy các lệnh sau trong terminal:

sudo apt update
sudo apt install nodejs npm

Để giả lập một API như https://ipinfo.io/1.1.1.1/json, bạn có thể sử dụng một công cụ giả lập API như json-server. Dưới đây là cách bạn có thể làm điều này:

npm install -g json-server

Ví dụ.

shell> npm install -g json-server
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: 'json-server@1.0.0-alpha.23',
npm WARN EBADENGINE   required: { node: '>=18.3' },
npm WARN EBADENGINE   current: { node: 'v12.22.9', npm: '8.5.1' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: '@tinyhttp/app@2.2.3',
npm WARN EBADENGINE   required: { node: '>=14.21.3' },
npm WARN EBADENGINE   current: { node: 'v12.22.9', npm: '8.5.1' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: 'dot-prop@8.0.2',
npm WARN EBADENGINE   required: { node: '>=16' },
npm WARN EBADENGINE   current: { node: 'v12.22.9', npm: '8.5.1' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: 'inflection@3.0.0',
npm WARN EBADENGINE   required: { node: '>=18.0.0' },
npm WARN EBADENGINE   current: { node: 'v12.22.9', npm: '8.5.1' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: 'lowdb@7.0.1',
npm WARN EBADENGINE   required: { node: '>=18' },
npm WARN EBADENGINE   current: { node: 'v12.22.9', npm: '8.5.1' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: 'sort-on@6.0.0',
npm WARN EBADENGINE   required: { node: '>=18' },
npm WARN EBADENGINE   current: { node: 'v12.22.9', npm: '8.5.1' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: 'mime@4.0.1',
npm WARN EBADENGINE   required: { node: '>=16' },
npm WARN EBADENGINE   current: { node: 'v12.22.9', npm: '8.5.1' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: 'type-fest@3.13.1',
npm WARN EBADENGINE   required: { node: '>=14.16' },
npm WARN EBADENGINE   current: { node: 'v12.22.9', npm: '8.5.1' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: 'steno@4.0.2',
npm WARN EBADENGINE   required: { node: '>=18' },
npm WARN EBADENGINE   current: { node: 'v12.22.9', npm: '8.5.1' }
npm WARN EBADENGINE }

added 54 packages, and audited 55 packages in 8s

14 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Nâng cấp Node.js lên phiên bản mới nhất để có thể hỗ trợ toán tử nullish coalescing.

Đầu tiên, cài đặt nvm bằng cách chạy lệnh sau trong terminal:

shell> curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 14926  100 14926    0     0  27822      0 --:--:-- --:--:-- --:--:-- 27847
=> Downloading nvm from git to '/root/.nvm'
=> Cloning into '/root/.nvm'...
remote: Enumerating objects: 365, done.
remote: Counting objects: 100% (365/365), done.
remote: Compressing objects: 100% (312/312), done.
remote: Total 365 (delta 43), reused 168 (delta 27), pack-reused 0
Receiving objects: 100% (365/365), 365.21 KiB | 2.33 MiB/s, done.
Resolving deltas: 100% (43/43), done.
* (HEAD detached at FETCH_HEAD)
  master
=> Compressing and cleaning up git repository

=> Appending nvm source string to /root/.bashrc
=> Appending bash_completion source string to /root/.bashrc
=> You currently have modules installed globally with `npm`. These will no
=> longer be linked to the active version of Node when you install a new node
=> with `nvm`; and they may (depending on how you construct your `$PATH`)
=> override the binaries of modules installed with `nvm`:

/usr/local/lib
└── json-server@1.0.0-alpha.23
=> If you wish to uninstall them at a later point (or re-install them under your
=> `nvm` Nodes), you can remove them from the system Node as follows:

     $ nvm use system
     $ npm uninstall -g a_module

=> Close and reopen your terminal to start using nvm or run the following to use it now:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

Hãy kiểm tra xem nvm đã được cài đặt chưa bằng cách mở một cửa sổ terminal mới và chạy lệnh sau:

command -v nvm

Nếu nvm đã được cài đặt, lệnh trên sẽ in ra nvm. Nếu không, bạn sẽ cần cài đặt nvm.

Để cài đặt nvm, bạn có thể sử dụng lệnh curl hoặc wget. Dưới đây là cách cài đặt nvm bằng curl:

shell> curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 14926  100 14926    0     0  77602      0 --:--:-- --:--:-- --:--:-- 77739
=> nvm is already installed in /root/.nvm, trying to update using git
=> => Compressing and cleaning up git repository

=> nvm source string already in /root/.bashrc
=> bash_completion source string already in /root/.bashrc
=> You currently have modules installed globally with `npm`. These will no
=> longer be linked to the active version of Node when you install a new node
=> with `nvm`; and they may (depending on how you construct your `$PATH`)
=> override the binaries of modules installed with `nvm`:

/usr/local/lib
└── json-server@1.0.0-alpha.23
=> If you wish to uninstall them at a later point (or re-install them under your
=> `nvm` Nodes), you can remove them from the system Node as follows:

     $ nvm use system
     $ npm uninstall -g a_module

=> Close and reopen your terminal to start using nvm or run the following to use it now:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

Sau khi cài đặt, bạn cần đóng và mở lại terminal hoặc chạy lệnh sau để có thể sử dụng nvm:

source ~/.bashrc

Cuối cùng, sau khi cài đặt và khởi tạo nvm, bạn có thể cài đặt Node.js bằng cách chạy lệnh sau:

shell> nvm install node
Downloading and installing node v21.6.2...
Downloading https://nodejs.org/dist/v21.6.2/node-v21.6.2-linux-x64.tar.xz...
################################################################################################################################################################# 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v21.6.2 (npm v10.2.4)
Creating default alias: default -> node (-> v21.6.2)

Tạo một file JSON với dữ liệu giả mạo. Ví dụ, bạn có thể tạo một file có tên db.json với nội dung sửa đổi country từ và city như sau:

{
  "1.1.1.1": {
    "ip": "1.1.1.1",
    "hostname": "one.one.one.one",
    "anycast": true,
    "city": "HCM City",
    "region": "New South Wales",
    "country": "VN",
    "loc": "-33.8592,151.2081",
    "org": "AS13335 Cloudflare, Inc.",
    "postal": "2000",
    "timezone": "Australia/Sydney",
    "readme": "https://ipinfo.io/missingauth"
  }
}

Chạy json-server với file JSON bạn vừa tạo:

shell> json-server --watch db.json
--watch/-w can be omitted, JSON Server 1+ watches for file changes by default
JSON Server started on PORT :3000
Press CTRL-C to stop
Watching db.json...

( ˶ˆ ᗜ ˆ˵ )

Index:
http://localhost:3000/

Static files:
Serving ./public directory if it exists

Endpoints:
http://localhost:3000/1.1.1.1

Bây giờ, bạn có thể truy cập http://localhost:3000/1.1.1.1 từ trình duyệt web hoặc từ mã của bạn để nhận dữ liệu giả mạo. Bạn cần cập nhật URL trong mã của bạn từ https://ipinfo.io/1.1.1.1/json thành http://localhost:3000/1.1.1.1 để sử dụng API giả mạo này.

Bạn cũng có thể kiểm thử tại localhost bằng lệnh curl bạn sẽ thấy nội dung trả về của API.

shell> curl http://localhost:3000/1.1.1.1
{
  "ip": "1.1.1.1",
  "hostname": "one.one.one.one",
  "anycast": true,
  "city": "HCM City",
  "region": "New South Wales",
  "country": "VN",
  "loc": "-33.8592,151.2081",
  "org": "AS13335 Cloudflare, Inc.",
  "postal": "2000",
  "timezone": "Australia/Sydney",
  "readme": "https://ipinfo.io/missingauth"
}

Chúc các bạn thành công.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

4,956FansLike
256FollowersFollow
223SubscribersSubscribe
spot_img

Related Stories