Skip to content

Commit

Permalink
Merge pull request #542 from bozzaj/custom-generate
Browse files Browse the repository at this point in the history
Add ability to use a field-specific custom generate function
  • Loading branch information
dev-embedthis authored Dec 27, 2024
2 parents 8eb0ec3 + ecf5d3e commit 1a526d0
Show file tree
Hide file tree
Showing 6 changed files with 106 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Model.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export type OneField = {
encode?: readonly (string | RegExp | number)[] | string
enum?: readonly string[]
filter?: boolean
generate?: string | boolean
generate?: string | boolean | function
hidden?: boolean
items?: OneField
map?: string
Expand Down
2 changes: 2 additions & 0 deletions src/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -1561,6 +1561,8 @@ export class Model {
let generate = field.generate
if (generate === true) {
value = this.table.generate()
} else if (typeof generate === 'function') {
value = generate()
} else if (generate == 'uuid') {
value = this.table.uuid()
} else if (generate == 'ulid') {
Expand Down
56 changes: 56 additions & 0 deletions test/custom-generate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
crypto.ts - CRUD with crypto
*/
import {AWS, Client, Match, Table, print, dump, delay, isV3, isV2} from './utils/init'
import {CustomGenerateSchema} from './schemas'

const table = new Table({
name: 'CustomGenerateTestTable',
client: Client,
partial: false,
schema: CustomGenerateSchema,
logger: true,
})

let User: any = null
let user: any
let users: any[]

test('Create Table', async () => {
if (!(await table.exists())) {
await table.createTable()
expect(await table.exists()).toBe(true)
}
User = table.getModel('User')
})

test('Create', async () => {
user = await User.create({name: 'Peter Smith'})
expect(user).toMatchObject({
name: 'Peter Smith',
})
})

test('Get', async () => {
user = await User.get({id: user.id})
expect(user).toMatchObject({
name: 'Peter Smith',
})
console.log(user)
expect(user.id).toMatch(Match.customUuid)
})

test('Get raw ', async () => {
user = await User.get({id: user.id}, {hidden: true, parse: false})
if (isV3()) {
expect(user.pk.S).toMatch(/^User#/)
}
if (isV2()) {
expect(user.pk).toMatch(/^User#/)
}
})

test('Destroy Table', async () => {
await table.deleteTable('DeleteTableForever')
expect(await table.exists()).toBe(false)
})
44 changes: 44 additions & 0 deletions test/schemas/customGenerateSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@

import Crypto from 'crypto'

/*
Generates a simple uuidv7-like String.
Note: This method is simplified for testing only!
*/
function customId() {
const randomBytes = Crypto.randomBytes(10);

randomBytes[2] = randomBytes[2] & 0x3f | 0x80;

const result = Date.now().toString(16).padStart(12, "0")
+ "7"
+ randomBytes.toString("hex").substring(1)

return [
result.substring(0, 8),
result.substring(8, 12),
result.substring(12, 16),
result.substring(16, 20),
result.substring(20)
].join("-")
}

/*
Schema to use with custom generate function
*/
export default {
format: 'onetable:1.1.0',
version: '0.0.1',
indexes: {
primary: {hash: 'pk', sort: 'sk'},
},
models: {
User: {
pk: {type: String, value: '${_type}#${id}'},
sk: {type: String, value: '${_type}#'},
id: {type: String, generate: customId},
name: {type: String},
},
},
params: {},
}
2 changes: 2 additions & 0 deletions test/schemas/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import CryptoSchema from './cryptoSchema'
import CustomGenerateSchema from './customGenerateSchema'
import DataTypesSchema from './dataTypesSchema'
import DefaultSchema from './defaultSchema'
import FullSchema from './fullSchema'
Expand All @@ -15,6 +16,7 @@ import ArrayItemsSchema from './arrayItemsSchema'
export {
ArrayItemsSchema,
CryptoSchema,
CustomGenerateSchema,
DataTypesSchema,
DefaultSchema,
FullSchema,
Expand Down
1 change: 1 addition & 0 deletions test/utils/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ const delay = async (time) => {
const Match = {
ulid: /^[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}$/,
uuid: /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i,
customUuid: /^[a-f0-9]{8}-[a-f0-9]{4}-7[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i,
email: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
name: /^[a-z ,.'-]+$/i,
address: /[a-z0-9 ,.-]+$/,
Expand Down

0 comments on commit 1a526d0

Please sign in to comment.