Skip to content
This repository was archived by the owner on Jun 9, 2025. It is now read-only.

feat: add KV store #89

Closed
wants to merge 4 commits into from
Closed
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
83 changes: 82 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,16 @@
"test": "test"
},
"dependencies": {
"is-promise": "^4.0.0"
"is-promise": "^4.0.0",
"node-fetch": "^2.6.1"
},
"devDependencies": {
"@commitlint/cli": "^12.0.0",
"@commitlint/config-conventional": "^12.0.0",
"@netlify/eslint-config-node": "^3.1.4",
"ava": "^2.4.0",
"husky": "^4.3.8",
"nock": "^13.1.0",
"nyc": "^15.0.0"
},
"engines": {
Expand Down
2 changes: 2 additions & 0 deletions src/lib/consts.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ const BUILDER_FUNCTIONS_FLAG = true
const HTTP_STATUS_METHOD_NOT_ALLOWED = 405
const HTTP_STATUS_OK = 200
const METADATA_VERSION = 1
const STORE_ENDPOINT = 'https://functions-kv.netlify.app'

module.exports = {
BUILDER_FUNCTIONS_FLAG,
HTTP_STATUS_METHOD_NOT_ALLOWED,
HTTP_STATUS_OK,
METADATA_VERSION,
STORE_ENDPOINT,
}
17 changes: 17 additions & 0 deletions src/lib/store.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export interface ObjectDescription {
lastModified: string
key: string
}
export interface ListResponse<T = any> {
count: number
objects: Array<ObjectDescription>
}
export interface Store {
get<T = any>(key: string): Promise<T>
set<T = any>(key: string, value: T): Promise<boolean>
delete(key: string): Promise<boolean>
list(prefix: string): Promise<ListResponse>
patch<T extends Record<string, any>>(key: string, value: Partial<T>): Promise<T>
}

export function getStore(context: HandlerContext): Store
95 changes: 95 additions & 0 deletions src/lib/store.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// @ts-check

const process = require('process')

const { default: fetch } = require('node-fetch')

const { STORE_ENDPOINT } = require('./consts')

const isValidKey = (key) => key && typeof key === 'string'

/**
* A key-value store object. Expects a context with `context.clientContext.store.token`
*
* @param {import("../..").HandlerContext} context
* @returns Promise<Store>
*/
module.exports.getStore = function getStore(context) {
const headers = { authorization: `Bearer ${context.clientContext.blobstore.token}` }
const endpoint = process.env.STORE_ENDPOINT || STORE_ENDPOINT
return {
async get(key) {
if (!isValidKey(key)) {
throw new Error('Invalid key')
}
const response = await fetch(`${endpoint}/item/${encodeURIComponent(key)}`, { headers })
if (response.status === 404) {
return
}
if (!response.ok) {
throw new Error(`There was an error loading the value for key ${key}: ${response.statusText}`)
}
try {
return response.json()
} catch (error) {
throw new Error(`Error parsing value for key ${key}`)
}
},
async set(key, value) {
if (!isValidKey(key)) {
throw new Error('Invalid key')
}

let body
try {
body = JSON.stringify(value)
} catch (error) {
throw new Error(`Could not serialize value for key ${key}. Item must be JSON-serializable`)
}
const response = await fetch(`${endpoint}/item/${encodeURIComponent(key)}`, {
method: 'PUT',
headers,
body,
})
if (!response.ok) {
throw new Error(`There was an error setting key ${key}: ${response.statusText}`)
}
return true
},

async delete(key) {
if (!isValidKey(key)) {
throw new Error('Invalid key')
}

const response = await fetch(`${endpoint}/item/${encodeURIComponent(key)}`, { method: 'DELETE', headers })

if (response.status === 404) {
return false
}

if (!response.ok) {
throw new Error(`There was an error setting key ${key}: ${response.statusText}`)
}
return true
},

async list(prefix) {
if (!isValidKey(prefix)) {
throw new Error('Invalid key')
}
const response = await fetch(`${endpoint}/list/${encodeURIComponent(prefix)}`, { headers })
if (response.status === 404) {
return { count: 0, objects: [] }
}
if (!response.ok) {
throw new Error(`There was an error loading the value for prefix ${prefix}: ${response.statusText}`)
}
try {
return response.json()
} catch (error) {
throw new Error(`Error parsing value for key ${prefix}`)
}
},
}
}
1 change: 1 addition & 0 deletions src/main.d.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './lib/builder'
export * from './lib/store'
export * from './function'
3 changes: 2 additions & 1 deletion src/main.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const { builder } = require('./lib/builder')
const { getStore } = require('./lib/store')

module.exports = { builder }
module.exports = { builder, getStore }
Loading