How to start using data validation in kv?

Hey fellows! I want to dive into data validation. Any experience or suggestions? Feel free to post a commented version of the repository I provided here:
import Post from '@/modules/post/model.ts'

import { setData, getData, listData, removeData } from '@/helpers/data.ts'

type PostParams = {
blogSlug?: string
postSlug?: string
postInput?: Post
}

class PostRepository {
static async createPost({ postInput, blogSlug }: PostParams) {
const key = ['blog', blogSlug as string, 'post', postInput?.slug as string]
const result = await setData({ key, value: postInput })
if (result.ok) return await getData({ key })
}

static async listPosts({ blogSlug }: PostParams) {
const prefix = ['blog', blogSlug as string, 'post']
return await listData({ prefix })
}

static async showPost({ blogSlug, postSlug }: PostParams) {
const key = ['blog', blogSlug as string, 'post', postSlug as string]
return await getData({ key })
}

static async updatePost({ postInput, blogSlug, postSlug }: PostParams) {
const key = ['blog', blogSlug as string, 'post', postSlug as string]
return await setData({ key, value: postInput })
}

static async deletePost({ blogSlug, postSlug }: PostParams) {
const key = ['blog', blogSlug as string, 'post', postSlug as string]
await removeData({ key })
}
}

export default PostRepository
import Post from '@/modules/post/model.ts'

import { setData, getData, listData, removeData } from '@/helpers/data.ts'

type PostParams = {
blogSlug?: string
postSlug?: string
postInput?: Post
}

class PostRepository {
static async createPost({ postInput, blogSlug }: PostParams) {
const key = ['blog', blogSlug as string, 'post', postInput?.slug as string]
const result = await setData({ key, value: postInput })
if (result.ok) return await getData({ key })
}

static async listPosts({ blogSlug }: PostParams) {
const prefix = ['blog', blogSlug as string, 'post']
return await listData({ prefix })
}

static async showPost({ blogSlug, postSlug }: PostParams) {
const key = ['blog', blogSlug as string, 'post', postSlug as string]
return await getData({ key })
}

static async updatePost({ postInput, blogSlug, postSlug }: PostParams) {
const key = ['blog', blogSlug as string, 'post', postSlug as string]
return await setData({ key, value: postInput })
}

static async deletePost({ blogSlug, postSlug }: PostParams) {
const key = ['blog', blogSlug as string, 'post', postSlug as string]
await removeData({ key })
}
}

export default PostRepository
Thank you!
TM
Timo Martinson50d ago
This is my model:
type Post = {
title: string
slug: string
content: string
draft: boolean
publishedAt: Date
}
type Post = {
title: string
slug: string
content: string
draft: boolean
publishedAt: Date
}
DAH
Deno AI Helper50d ago
Hello there! 🦕 To start using data validation in Deno KV, you can follow a few strategies as suggested by the documentation. When you're dealing with TypeScript, you can use interfaces or classes to describe the shape and behavior of objects in your programs, which can serve as a form of data validation. Here's a step-by-step guide based on the documentation: 1. Define Your Data Models: You've already defined a Post model, which is great. Ensure that your model accurately represents the data structure you want to store in Deno KV. 2. Type Assertions: When retrieving objects from Deno KV, you can use type assertions to inform TypeScript about the shape of an object. For example:
const post = await kv.get(["blog", "my-blog", "post", "my-post"]) as Post;

const post = await kv.get(["blog", "my-blog", "post", "my-post"]) as Post;

3. Type Parameters: Alternatively, you can specify an optional type parameter for the get method to automatically cast the returned value to the specified type:
const post = await kv.get<Post>(["blog", "my-blog", "post", "my-post"]);

const post = await kv.get<Post>(["blog", "my-blog", "post", "my-post"]);

4. Service Layer: For more complex validation that involves business logic, you can create a set of functions or a service layer that operates on your data transfer objects (DTOs). This layer can ensure that the data being passed around is valid and not merely typed correctly. 5. Validation Functions: Develop pure functions that can validate your DTOs. These functions can check for required fields, data formats, and other business rules before you save or retrieve data from Deno KV. 6. Use the Service Layer in Your Repository: In your PostRepository, you can use these validation functions to validate postInput before calling setData and after retrieving data with getData. Here's an example of how you might
DAH
Deno AI Helper50d ago
integrate a simple validation function into your PostRepository:
import Post from '@/modules/post/model.ts'
import { validatePost } from '@/validators/postValidator.ts' // This is a hypothetical validator function you would create

// ... rest of your repository code ...

class PostRepository {
static async createPost({ postInput, blogSlug }: PostParams) {
if (!validatePost(postInput)) {
throw new Error('Invalid post data');
}
// ... rest of the createPost method ...
}

// ... rest of the repository methods ...
}

export default PostRepository
import Post from '@/modules/post/model.ts'
import { validatePost } from '@/validators/postValidator.ts' // This is a hypothetical validator function you would create

// ... rest of your repository code ...

class PostRepository {
static async createPost({ postInput, blogSlug }: PostParams) {
if (!validatePost(postInput)) {
throw new Error('Invalid post data');
}
// ... rest of the createPost method ...
}

// ... rest of the repository methods ...
}

export default PostRepository
Remember, the actual implementation of your validation logic will depend on the specific requirements of your application. The above steps are a general guide to get you started with data validation in Deno KV as suggested by the documentation. Keep in mind that Deno KV is currently in beta and the APIs are subject to change. Always ensure you're using the --unstable flag when working with Deno KV. Happy coding! 🦕
L
Leokuma49d ago
This might be a useful resource: https://github.com/oliver-oloughlin/kvdex
GitHub
GitHub - oliver-oloughlin/kvdex: A high-level abstraction layer for...
A high-level abstraction layer for Deno KV with zero third-party dependencies by default 🦕🗝️ - oliver-oloughlin/kvdex
More Posts
deno cache isn't working from vscodeWhen initializing a new fresh project from the cli script `deno run -A -r https://fresh.deno.dev` an`.read()` method in `Deno.Conn` or `Deno.FsFile` in Deno 2.0After `Deno.Reader` is removed in v2.0, will we still be able to use `.read()` method in `Deno.Conn`Stuck trying to install a JSR package with its dependencies and use it in a browserI published https://jsr.io/@datasette/table to JSR - an experimental web component package - and nowList of available demo commandsIs there a programmatic way to get a list of all possible deno commands? Something like: ```ts consServer isolates cause Socket.IO problemsHi guys, I have a simple socket.IO program that basically broadcasts the changes in any one client'Puppeteer: "BadResource: Bad resource ID" on UbuntuHello, i just switched my server os over to ubuntu server 23.10. When executing my script, it immediUnable to use Deno.createHttpClient without deprecated flag --unstableI expected it to be behind the newer `--unstable-net` flagMultiple JsRuntimes crashe if first is not dropped before a second is created and ranIn my application, I want an `op2` to take in a function which will be stored in a struct as a `GlobStructure microservicesHi, how would you structure a Deno microservice repository with a good developer experience (good dGet image from automated downloadI have this page which displays a render using threejs and renders it into a png and downloads it. iGet image data from automated downloadI have this page which displays a render using threejs and renders it into a png and downloads it. iWait until Deno.Command process has exitedHow would i stop code execution until the process has exited? since its not a promise i cant just do