Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add myjson.online driver #366

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions docs/content/6.drivers/myjson.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# myJson

::alert
This is an experimental driver! This driver has not been fully tested with the myJson APIs.
::

Store JSON data via [myJson](https://myjson.online).

```js
import { createStorage } from "unstorage";
import myJsonDriver from "unstorage/drivers/myjson";

const storage = createStorage({
driver: myJsonDriver({
accessToken: "ACCESS TOKEN",
collectionId: "COLLECTION ID",
}),
});
```

**Options:**

- `accessToken`: Access Token for the collection (**required**)
- `collectionId`: Collection ID for all requests (**required**)
- `headers`: Custom headers to send on all requests

**Supported HTTP Methods:**

- `getItem`: Get a record. Returns deserialized value if response is ok
- `hasItem`: Returns `true` if response is ok (200)
- `setItem`: Create a record if record doesn't exists, update specific property of the record if `patch` option is `true`, or update a record.
- `removeItem`: Delete a record.
- `clear`: Delete all records in a collection.

**Transaction Options:**

- `headers`: Custom headers to be sent on each operation (`getItem`, `setItem`, etc)
110 changes: 110 additions & 0 deletions src/drivers/myjson.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { defineDriver } from "./utils";
import { $fetch as _fetch } from "ofetch";
import { joinURL } from "ufo";

export interface myJsonOptions {
collectionId: string;
accessToken: string;
headers?: Record<string, string>;
}

const RECORDS_BASE_URL = "https://api.myjson.online/v1/records";
const DRIVER_NAME = "http";

export default defineDriver((opts: myJsonOptions) => {
const r = (key: string = "") =>
joinURL(RECORDS_BASE_URL, key.replace(/:/g, "/"));

opts.headers ??= {};
opts.headers["x-collection-access-token"] = opts.accessToken;

return {
name: DRIVER_NAME,
options: opts,
async hasItem(key, topts) {
return _fetch(r(key), {
method: "HEAD",
headers: { ...opts.headers, ...topts.headers },
redirect: "follow",
})
.then(() => true)
.catch(() => false);
},
async getItem(key, tops = {}) {
return await _fetch(r(key), {
headers: {
...opts.headers,
...tops.headers,
"Content-Type": "application/json",
},
redirect: "follow",
});
},
async getItemRaw(key, topts) {
return await _fetch(r(key), {
headers: {
accept: "application/octet-stream",
...opts.headers,
...topts.headers,
},
redirect: "follow",
});
},
async setItem(key, value, topts: { patch?: true }) {
let method = "POST";
const urlencoded = new URLSearchParams();

urlencoded.append("jsonData", value);
urlencoded.append("collectionId", opts.collectionId);

if (topts.patch) {
method = "PATCH";
urlencoded.append("jsonData", value);
} else if (this.hasItem(key, opts)) {
method = "PUT";
urlencoded.append("jsonData", value);
}

return await _fetch(r(key), {
method,
headers: { ...opts.headers, "Content-Type": "x-www-form-urlencoded" },
body: urlencoded,
redirect: "follow",
});
},
async setItems(items, topts) {
await Promise.all(
items.map(
(item) =>
this.setItem && this.setItem(item.key, item.value, topts || {})
)
);
},
async removeItem(key, topts) {
await _fetch(r(key), {
method: "DELETE",
headers: { ...opts.headers, ...topts.headers },
redirect: "follow",
});
},
async getKeys(collectionId, topts) {
const url = `https://api.myjson.online/v1/collections/${
collectionId || opts.collectionId
}/records`;

const value = await _fetch(url, {
headers: { ...opts.headers, ...topts.headers },
redirect: "follow",
});

return Array.isArray(value) ? value : [];
},
async clear(base, topts) {
const keys = await this.getKeys(base || opts.collectionId, topts);

await Promise.all(
keys.map((key) => this.removeItem && this.removeItem(key, topts))
);
},
};
});
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export const builtinDrivers = {
lruCache: "unstorage/drivers/lru-cache",
memory: "unstorage/drivers/memory",
mongodb: "unstorage/drivers/mongodb",
myjson: "unstorage/drivers/myjson",
netlifyBlobs: "unstorage/drivers/netlify-blobs",
overlay: "unstorage/drivers/overlay",
planetscale: "unstorage/drivers/planetscale",
Expand Down Expand Up @@ -72,6 +73,7 @@ export type BuiltinDriverOptions = {
lruCache: ExtractOpts<(typeof import("./drivers/lru-cache"))["default"]>;
memory: ExtractOpts<(typeof import("./drivers/memory"))["default"]>;
mongodb: ExtractOpts<(typeof import("./drivers/mongodb"))["default"]>;
myjson: ExtractOpts<(typeof import("./drivers/myjson"))["default"]>;
netlifyBlobs: ExtractOpts<
(typeof import("./drivers/netlify-blobs"))["default"]
>;
Expand Down
12 changes: 12 additions & 0 deletions test/drivers/myjson.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { describe, afterAll } from "vitest";
import driver from "../../src/drivers/myjson";
import { testDriver } from "./utils";

describe("drivers: myjson", async () => {
testDriver({
driver: driver({
accessToken: "YOUR ACCESS_TOKEN",
collectionId: "YOUR COLLECTION_ID",
}),
});
});
Loading