Gathering detailed insights and metrics for pocket-rest-lib
Gathering detailed insights and metrics for pocket-rest-lib
Gathering detailed insights and metrics for pocket-rest-lib
Gathering detailed insights and metrics for pocket-rest-lib
npm install pocket-rest-lib
Typescript
Module System
Min. Node Version
Node Version
NPM Version
TypeScript (95.08%)
JavaScript (3.77%)
Shell (1.15%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
1 Stars
14 Commits
1 Watchers
1 Branches
1 Contributors
Updated on Nov 16, 2024
Latest Version
1.0.4
Package Id
pocket-rest-lib@1.0.4
Unpacked Size
53.65 kB
Size
10.24 kB
File Count
10
NPM Version
10.9.0
Node Version
20.17.0
Published on
Nov 16, 2024
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
23
Pocket REST Lib is an NPM library designed to simplify API interactions through a structured and consistent way to perform CRUD operations and authentication with minimal effort. It is totally inspired by PocketBase's amazingly simple request mapping. It eliminates the need to manually design and call APIs, letting the developers focus on fast development.
While doing academic projects, I found it wasting to think on how to map the API requests every time I made some application. PocketBase's simplified mapping and fetching got me really fascinated. So, I thought why not just implement a REST mapping much like this one and integrate with my backend?
create
, update
, delete
, or get
functions.try-catch
blocks.fetch
; no need for additional HTTP libraries like Axios
.authWithPassword
.jwt-decode
library as a dependency.To install the library, run:
1npm install pocket-rest-lib
Your backend must follow the request mapping structure show in this documentation to integrate with this library. Refer to this Section: API Reference
1import PocketRestLib from 'pocket-rest-lib';
1const client = new PocketRestLib('https://your-backend-url.com');
You can manage a specific collection by calling the collection
method:
1const users = client.collection('users');
The Collection
object provides methods to perform CRUD operations.
1await users.create({ username: 'john_doe', email: 'john@example.com' });
1const user = await users.getOne('12345');
1const userList = await users.getList(1, 20, { filter: "verified=true" });
1await users.update('12345', { username: 'john_updated' });
1await users.delete('12345');
Retrieve all records (paginated internally):
1const allUsers = await users.getFullList();
Retrieve the first item matching a filter:
1const firstUser = await users.getFirstListItem("email='john@example.com'");
Authenticate with a username and password:
1const authResponse = await users.authWithPassword('john@example.com', 'securepassword');
Authentication tokens are automatically stored and reused for subsequent requests.
My realtime implementation uses WebSocket connections unlike PocketBase's SSE. So, it's different.
Subscribe to real-time updates on a collection:
1const subscription = users.subscribe(); 2 3subscription.onCreate((data) => { 4 console.log('Record created:', data); 5}); 6 7subscription.onUpdate((data) => { 8 console.log('Record updated:', data); 9}); 10 11subscription.onDelete((data) => { 12 console.log('Record deleted:', data); 13});
To unsubscribe:
1users.unsubscribe();
Generate file URLs for specific records:
1const fileUrl = users.file('recordId', 'filename.jpg'); 2console.log(fileUrl); // Outputs: https://your-backend-url.com/api/files/users/recordId/filename.jpg
Method | Description |
---|---|
create(data, auth?) | Create a new record. |
update(id, data, auth?) | Update a record by ID. |
delete(id, auth?) | Delete a record by ID. |
getOne(id, options?, auth?) | Retrieve a single record by ID. |
getList(page, perPage, options?, auth?) | Retrieve a paginated list of records. |
getFullList(options?, auth?) | Retrieve all records (paginated internally). |
getFirstListItem(filter, options?, auth?) | Retrieve the first matching record. |
subscribe() | Subscribe to real-time updates via WebSocket. |
unsubscribe() | Unsubscribe from WebSocket updates. |
authWithPassword(identity, password) | Authenticate using email and password. |
file(recordId, filename) | Generate a file URL for a specific record. |
Method | Description |
---|---|
loadFromCookie(cookie, key?) | Load authentication from a cookie. |
exportToCookie(options?, key?) | Export authentication to a cookie. |
save(token, model) | Save authentication token and model to storage. |
clear() | Clear authentication data from storage. |
The crud
utility simplifies HTTP methods.
Function | Description |
---|---|
GET(url) | Perform a GET request to the specified URL. |
POST(url, body) | Perform a POST request with a JSON or FormData body. |
PATCH(url, body) | Perform a PATCH request with a JSON or FormData body. |
DELETE(url) | Perform a DELETE request to the specified URL. |
Errors are logged to the console. To handle errors programmatically, you can modify the crud
functions or wrap calls in a try-catch
block.
1import PocketRestLib from 'pocket-rest-lib'; 2 3const client = new PocketRestLib('https://your-backend-url.com'); 4const users = client.collection('users'); 5 6(async () => { 7 // Authenticate 8 const auth = await users.authWithPassword('admin@example.com', 'adminpassword'); 9 10 // Create a new user 11 await users.create({ username: 'new_user', email: 'new@example.com' }); 12 13 // Retrieve user list 14 const userList = await users.getList(1, 10, { sort: '-created' }); 15 16 console.log(userList); 17 18 // Subscribe to real-time updates 19 const subscription = users.subscribe(); 20 21 subscription.onCreate((data) => console.log('User created:', data)); 22})();
Here's a detailed API mapping documentation. This is pretty much similar to PocketBase's:
/api/collections/:collectionName/records
Retrieve a paginated list of records from a specific collection.
Parameter | Type | Description | Default |
---|---|---|---|
page | Number | The page (offset) of the paginated list. | 1 |
perPage | Number | Maximum number of records per page. | 30 |
sort | String | Sort order of the records. Use - for DESC or + (default) for ASC. | None |
filter | String | Apply filters to the records. Example: filter=(id='abc' && created>'2022-01-01') . | None |
expand | String | Expand nested relations up to 6 levels. Example: expand=relField1,relField2.subRelField . | None |
fields | String | Specify which fields to include in the response. Example: fields=*,expand.relField.name . | All |
skipTotal | Boolean | Skip the total counts query for faster performance. | false |
@random
id
username
email
emailVisibility
verified
created
updated
name
avatar
1GET /api/collections/users/records?page=1&perPage=10&sort=-created&filter=(verified=true)&expand=profile
/api/collections/:collectionName/records/:id
Retrieve a single record by its ID.
Parameter | Type | Description |
---|---|---|
collectionName | String | The name of the collection. |
id | String | The ID of the record. |
1GET /api/collections/users/records/12345
/api/collections/:collectionName/records
Create a new record in a collection.
Parameter | Type | Description |
---|---|---|
collectionName | String | The name of the collection. |
Send a JSON object containing the data for the new record.
1POST /api/collections/users/records
2Content-Type: application/json
3
4{
5 "username": "john_doe",
6 "email": "john@example.com",
7 "verified": true
8}
/api/collections/:collectionName/records/:id
Update an existing record in a collection.
Parameter | Type | Description |
---|---|---|
collectionName | String | The name of the collection. |
id | String | The ID of the record. |
Send a JSON object containing the fields to update.
1PATCH /api/collections/users/records/12345
2Content-Type: application/json
3
4{
5 "username": "john_updated"
6}
/api/collections/:collectionName/records/:id
Delete a record from a collection by its ID.
Parameter | Type | Description |
---|---|---|
collectionName | String | The name of the collection. |
id | String | The ID of the record. |
1DELETE /api/collections/users/records/12345
page
: Specifies the current page number (default: 1).perPage
: Specifies the number of records per page (default: 30).Use the sort
parameter to sort records by attributes. Prefix with -
for DESC or leave it empty for ASC.
1?sort=-created,id
Use the filter
parameter to filter records using logical operators.
1?filter=(id='12345' && verified=true)
Use the expand
parameter to include related fields.
1?expand=profile,profile.address
Use the fields
parameter to specify which fields to return.
1?fields=*,profile.name,profile.email
Set skipTotal=true
to speed up queries by skipping total count calculations. This is ideal for cursor-based pagination.
expand
with caution for deep relations to prevent performance issues.Contributions are very much welcome! Feel free to open issues or submit pull requests
Inspired by the PocketBase ecosystem. Special thanks to developers who value simplicity and efficiency.
No vulnerabilities found.
No security vulnerabilities found.