import * as keywork from "https://deno.land/x/keywork@v6.0.1/collections/mod.ts";
The missing piece that unlocks the full power of storing and querying data from your Worker. Keywork Collections are a NoSQL, eventually-consistent ODM for Cloudflare's Worker KV. With an API reminiscent of Firebase and MongoDB, Keywork Collections are perfect for migrating your existing backend to Cloudflare's network.
The KeyworkCollection
class extends the Worker KV API without abstracting away important details.
Using Keywork collections from within a Cloudflare Worker.
compatibility_date = "2022-02-13"
name = "example-app"
route = "https://example.com/api/users/*"
kv_namespaces = [
{ binding = "users", id = "abcd123...", preview_id = "efgh456..."},
]
Creating a advanced request handler with a Keywork Collection.
import { StatusCodes } from 'http-status-codes'
import { KeyworkCollection } from '@keywork/collections'
import { KeyworkResourceError } from 'keywork/errors'
import { KeyworkRequestHandler, parsePathname } from 'keywork'
interface ExampleAppBindings {
exampleApp: KVNamespace
}
interface GetUserParams {
userID: string
}
interface ExampleUser {
firstName: string
lastName: string
role: 'member' | 'admin'
plan: 'free' | 'paid'
}
class UserAPIHandler extends KeyworkRequestHandler<ExampleAppBindings> {
async onRequestGet({ request, env }: IncomingRequestData<ExampleAppBindings>) {
const { params } = parsePathname<GetUserParams>('/users/:userID', request)
const usersCollection = new KeyworkCollection<ExampleUser>(env.exampleApp, 'users')
const userRef = usersCollection.createDocumentReference(params.userID)
const userSnapshot = await userRef.fetchSnapshot()
if (!userSnapshot.exists) {
throw new KeyworkResourceError('User does not exist', StatusCodes.BAD_REQUEST)
}
const user = userSnapshot.value
if (user.plan !== 'paid') {
throw new KeyworkResourceError('You must have a paid plan', StatusCodes.PAYMENT_REQUIRED)
}
if (user.role !== 'admin') {
throw new KeyworkResourceError('Only an admin can access this page', StatusCodes.FORBIDDEN)
}
}
}
export default UserAPIHandler
Classes
Creates a database instance backed by a Cloudflare KV namespace. | |
Creates an instance associated with specific document within a Cloudflare KV. |
Functions
Attempts to parse a given value's serialization type. | |
Generates a new document metadata. | |
Checks whether a given value and deserialization transformer is ETaggable. |
Interfaces
Metadata associated with a specific | |