Browse Source

Improve type safety

Allow resource schemata to be run via valibot's Output.
master
TheoryOfNekomata 9 months ago
parent
commit
2e296e7c15
2 changed files with 8 additions and 8 deletions
  1. +4
    -4
      src/core.ts
  2. +4
    -4
      src/server.ts

+ 4
- 4
src/core.ts View File

@@ -27,7 +27,7 @@ export interface Resource {
routeName?: string;
dataSource: DataSource;
newId(dataSource: DataSource): string | number | unknown;
schema: Parameters<typeof v.object>[0];
schema: v.BaseSchema;
}

interface GenerationStrategy {
@@ -38,7 +38,7 @@ interface IdParams {
generationStrategy: GenerationStrategy;
}

export const resource = (schema: Parameters<typeof v.object>[0]) => {
export const resource = <T extends v.BaseSchema>(schema: T) => {
let theIdAttr: string;
let theItemName: string;
let theCollectionName: string;
@@ -56,7 +56,7 @@ export const resource = (schema: Parameters<typeof v.object>[0]) => {
return idGenerationStrategy(dataSource);
},
fullText(fullTextAttr: string) {
if (schema[fullTextAttr]?.type === 'string') {
if (schema.type === 'object' && (schema as unknown as v.ObjectSchema<Record<string, v.BaseSchema>, undefined, Record<string, string>>).entries[fullTextAttr]?.type === 'string') {
fullTextAttrs.add(fullTextAttr);
return this;
}
@@ -155,7 +155,7 @@ const handleCreate = async (
return;
}

await v.parseAsync(v.object(resource.schema), bodyDeserialized, { abortEarly: false });
bodyDeserialized = await v.parseAsync(resource.schema, bodyDeserialized, { abortEarly: false });
} catch (err) {
res.statusCode = constants.HTTP_STATUS_BAD_REQUEST;
res.statusMessage = `Invalid ${resource.itemName}`;


+ 4
- 4
src/server.ts View File

@@ -50,9 +50,9 @@ const TEXT_SERIALIZER_PAIR = {
deserialize: <T>(str: string) => str as T
};

const Piano = resource({
const Piano = resource(v.object({
brand: v.string()
})
}))
.name('Piano')
.id('id', {
generationStrategy: autoIncrement,
@@ -60,13 +60,13 @@ const Piano = resource({

// TODO implement authentication and RBAC on each resource

const User = resource({
const User = resource(v.object({
firstName: v.string(),
middleName: v.string(),
lastName: v.string(),
bio: v.string(),
createdAt: v.date()
})
}))
.name('User')
.fullText('bio')
.id('id', {


Loading…
Cancel
Save