Merge pull request #2428 from automatisch/create-api-token-model

feat: Implement API Token model
This commit is contained in:
Ömer Faruk Aydın
2025-04-07 15:28:25 +02:00
committed by GitHub
5 changed files with 71 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
export async function up(knex) {
return knex.schema.createTable('api_tokens', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('gen_random_uuid()'));
table.string('token').notNullable().index();
table.timestamps(true, true);
});
}
export async function down(knex) {
return knex.schema.dropTable('api_tokens');
}

View File

@@ -0,0 +1,20 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`ApiToken model > jsonSchema should have correct validations 1`] = `
{
"properties": {
"id": {
"format": "uuid",
"type": "string",
},
"token": {
"minLength": 32,
"type": "string",
},
},
"required": [
"token",
],
"type": "object",
}
`;

View File

@@ -0,0 +1,17 @@
import Base from './base.js';
class ApiToken extends Base {
static tableName = 'api_tokens';
static jsonSchema = {
type: 'object',
required: ['token'],
properties: {
id: { type: 'string', format: 'uuid' },
token: { type: 'string', minLength: 32 },
},
};
}
export default ApiToken;

View File

@@ -0,0 +1,12 @@
import { describe, it, expect } from 'vitest';
import ApiToken from './api-token.js';
describe('ApiToken model', () => {
it('tableName should return correct name', () => {
expect(ApiToken.tableName).toBe('api_tokens');
});
it('jsonSchema should have correct validations', () => {
expect(ApiToken.jsonSchema).toMatchSnapshot();
});
});

View File

@@ -0,0 +1,10 @@
import crypto from 'crypto';
import ApiToken from '../../src/models/api-token.js';
export const createApiToken = async (params = {}) => {
params.token = params.token || crypto.randomBytes(48).toString('hex');
const apiToken = await ApiToken.query().insertAndFetch(params);
return apiToken;
};