π₯ π₯ π₯ A Free & Self-hostable Airtable Alternative
TypeScript airtableairtable-alternativeautomatic-apihacktoberfestlow-codeno-codeno-code-databaseno-code-platformpostgresqlrest-apirestful-apispreadsheetsqliteswagger
feat: Base - swagger-v3 api docs
Pranav C03badcbf2bbd
diff --git a/packages/nocodb/src/controllers/api-docs/api-docs.controller.ts b/packages/nocodb/src/controllers/api-docs/api-docs.controller.tsindex 53ec485313..57b5727d2a 100644--- a/packages/nocodb/src/controllers/api-docs/api-docs.controller.ts+++ b/packages/nocodb/src/controllers/api-docs/api-docs.controller.ts@@ -96,4 +96,42 @@ export class ApiDocsController {}),);}++ @Get(['/api/v3/meta/bases/:baseId/swagger.json'])+ @UseGuards(MetaApiLimiterGuard, GlobalGuard)+ @Acl('swaggerJson')+ async swaggerJsonV3(+ @TenantContext() context: NcContext,+ @Param('baseId') baseId: string,+ @Request() req,+ ) {+ const swagger = await this.apiDocsService.swaggerJsonV3(context, {+ baseId: baseId,+ siteUrl: req.ncSiteUrl,+ });++ return swagger;+ }++ @Get(['/api/v3/meta/bases/:baseId/swagger'])+ @UseGuards(PublicApiLimiterGuard)+ swaggerHtmlV3(@Param('baseId') baseId: string, @Response() res) {+ res.send(+ getSwaggerHtml({+ ncSiteUrl: process.env.NC_PUBLIC_URL || '',+ dashboardPath: Noco.getConfig().dashboardPath || '',+ }),+ );+ }++ @UseGuards(PublicApiLimiterGuard)+ @Get(['/api/v3/meta/bases/:baseId/redoc'])+ redocHtmlV3(@Param('baseId') baseId: string, @Response() res) {+ res.send(+ getRedocHtml({+ ncSiteUrl: process.env.NC_PUBLIC_URL || '',+ dashboardPath: Noco.getConfig().dashboardPath || '',+ }),+ );+ }}diff --git a/packages/nocodb/src/services/api-docs/api-docs.service.ts b/packages/nocodb/src/services/api-docs/api-docs.service.tsindex aaf61e8697..a9181e65be 100644--- a/packages/nocodb/src/services/api-docs/api-docs.service.ts+++ b/packages/nocodb/src/services/api-docs/api-docs.service.ts@@ -1,6 +1,7 @@import { Injectable } from '@nestjs/common';import getSwaggerJSON from './swagger/getSwaggerJSON';import getSwaggerJSONV2 from './swaggerV2/getSwaggerJSONV2';+import getSwaggerJSONV3 from './swaggerV3/getSwaggerJSONV3';import type { NcContext } from '~/interface/config';import { NcError } from '~/helpers/catchError';import { Base, Model } from '~/models';@@ -71,4 +72,37 @@ export class ApiDocsService {return swagger;}++ async swaggerJsonV3(+ context: NcContext,+ param: { baseId: string; siteUrl: string },+ ) {+ const base = await Base.get(context, param.baseId);++ if (!base) NcError.baseNotFound(param.baseId);++ const models = await Model.list(context, {+ base_id: param.baseId,+ source_id: null,+ });++ const swagger = await getSwaggerJSONV3(context, base, models);++ swagger.servers = [+ {+ url: param.siteUrl,+ },+ {+ url: '{customUrl}',+ variables: {+ customUrl: {+ default: param.siteUrl,+ description: 'Provide custom nocodb app base url',+ },+ },+ },+ ] as any;++ return swagger;+ }}diff --git a/packages/nocodb/src/services/api-docs/swaggerV3/getPathsV3.ts b/packages/nocodb/src/services/api-docs/swaggerV3/getPathsV3.tsnew file mode 100644index 0000000000..9c5a1e3da0--- /dev/null+++ b/packages/nocodb/src/services/api-docs/swaggerV3/getPathsV3.ts@@ -0,0 +1,30 @@+import { getModelPaths } from './templates/paths';+import type { Model } from '~/models';+import type { SwaggerColumn } from './getSwaggerColumnMetasV3';+import type { SwaggerView } from './getSwaggerJSONV3';+import type { NcContext } from '~/interface/config';+import Noco from '~/Noco';++export default async function getPathsV3(+ context: NcContext,+ {+ model,+ columns,+ views,+ }: {+ model: Model;+ columns: SwaggerColumn[];+ views: SwaggerView[];+ },+ _ncMeta = Noco.ncMeta,+) {+ const swaggerPaths = await getModelPaths(context, {+ tableName: model.title,+ tableId: model.id,+ views,+ type: model.type,+ columns,+ });++ return swaggerPaths;+}diff --git a/packages/nocodb/src/services/api-docs/swaggerV3/getSchemasV3.ts b/packages/nocodb/src/services/api-docs/swaggerV3/getSchemasV3.tsnew file mode 100644index 0000000000..8c79675f3f--- /dev/null+++ b/packages/nocodb/src/services/api-docs/swaggerV3/getSchemasV3.ts@@ -0,0 +1,29 @@+import { getModelSchemas } from './templates/schemas';+import type { Base, Model } from '~/models';++import type { SwaggerColumn } from './getSwaggerColumnMetasV3';+import type { SwaggerView } from './getSwaggerJSONV3';+import Noco from '~/Noco';++export default async function getSchemasV3(+ {+ base,+ model,+ columns,+ }: {+ base: Base;+ model: Model;+ columns: SwaggerColumn[];+ views: SwaggerView[];+ },+ _ncMeta = Noco.ncMeta,+) {+ const swaggerSchemas = getModelSchemas({+ tableName: model.title,+ orgs: 'v3',+ baseName: base.title,+ columns,+ });++ return swaggerSchemas;+}diff --git a/packages/nocodb/src/services/api-docs/swaggerV3/getSwaggerColumnMetasV3.ts b/packages/nocodb/src/services/api-docs/swaggerV3/getSwaggerColumnMetasV3.tsnew file mode 100644index 0000000000..82cec958b6--- /dev/null+++ b/packages/nocodb/src/services/api-docs/swaggerV3/getSwaggerColumnMetasV3.ts@@ -0,0 +1,128 @@+import { UITypes } from 'nocodb-sdk';+import { FormulaDataTypes } from 'nocodb-sdk';+import type { Base, Column, LinkToAnotherRecordColumn } from '~/models';+import type { NcContext } from '~/interface/config';+import SwaggerTypes from '~/db/sql-mgr/code/routers/xc-ts/SwaggerTypes';+import Noco from '~/Noco';++export default async (+ context: NcContext,+ columns: Column[],+ base: Base,+ ncMeta = Noco.ncMeta,+): Promise<SwaggerColumn> => {+ // extract dbtype based on column source+ const dbType = await base.getSources().then((sources) => {+ const sourceId = columns[0]?.source_id;+ return sources.find((s) => s.id === sourceId)?.type || sources[0]?.type;+ });+ return Promise.all(+ columns.map(async (c) => {+ const field: SwaggerColumn = {+ title: c.title,+ type: 'object',+ virtual: true,+ column: c,+ };++ switch (c.uidt) {+ case UITypes.LinkToAnotherRecord:+ {+ const colOpt = await c.getColOptions<LinkToAnotherRecordColumn>(+ context,+ ncMeta,+ );+ if (colOpt) {+ const relTable = await colOpt.getRelatedTable(context, ncMeta);+ field.type = undefined;+ field.$ref = `#/components/schemas/${relTable.title}Request`;+ }+ }+ break;+ case UITypes.Formula:+ // Extract type from parsed tree if available+ if (c.colOptions?.parsed_tree?.dataType) {+ const formulaDataType = c.colOptions.parsed_tree.dataType;+ switch (formulaDataType) {+ case FormulaDataTypes.NUMERIC:+ field.type = 'number';+ break;+ case FormulaDataTypes.STRING:+ field.type = 'string';+ break;+ case FormulaDataTypes.DATE:+ field.type = 'string';+ field.format = 'date-time';+ break;+ case FormulaDataTypes.BOOLEAN:+ case FormulaDataTypes.LOGICAL:+ case FormulaDataTypes.COND_EXP:+ field.type = 'boolean';+ break;+ case FormulaDataTypes.NULL:+ case FormulaDataTypes.UNKNOWN:+ default:+ field.type = 'string';+ break;+ }+ } else {+ // Fallback to string if no parsed tree available+ field.type = 'string';+ }+ break;+ case UITypes.Lookup:+ field.type = 'object';+ break;+ case UITypes.Rollup:+ field.type = 'number';+ break;+ case UITypes.Links:+ field.type = 'integer';+ break;+ case UITypes.Attachment:+ field.type = 'array';+ field.items = {+ $ref: `#/components/schemas/Attachment`,+ };+ field.virtual = false;+ break;+ case UITypes.Email:+ field.type = 'string';+ field.format = 'email';+ field.virtual = false;+ break;+ case UITypes.URL:+ field.type = 'string';+ field.format = 'uri';+ field.virtual = false;+ break;+ case UITypes.LastModifiedTime:+ case UITypes.CreatedTime:+ field.type = 'string';+ field.format = 'date-time';+ break;+ case UITypes.LastModifiedBy:+ case UITypes.CreatedBy:+ field.type = 'object';+ break;+ default:+ field.virtual = false;+ SwaggerTypes.setSwaggerType(c, field, dbType);+ break;+ }++ return field;+ }),+ );+};++export interface SwaggerColumn {+ type: any;+ title: string;+ description?: string;+ virtual?: boolean;+ $ref?: any;+ column: Column;+ items?: any;+ format?: string;+}diff --git a/packages/nocodb/src/services/api-docs/swaggerV3/getSwaggerJSONV3.ts b/packages/nocodb/src/services/api-docs/swaggerV3/getSwaggerJSONV3.tsnew file mode 100644index 0000000000..bc5cd77658--- /dev/null+++ b/packages/nocodb/src/services/api-docs/swaggerV3/getSwaggerJSONV3.ts@@ -0,0 +1,70 @@+import { ViewTypes } from 'nocodb-sdk';+import swaggerBase from './swagger-base-v3.json';+import getPathsV3 from './getPathsV3';+import getSchemasV3 from './getSchemasV3';+import getSwaggerColumnMetasV3 from './getSwaggerColumnMetasV3';+import type {+ Base,+ FormViewColumn,+ GalleryViewColumn,+ GridViewColumn,+ Model,+ View,+} from '~/models';+import type { NcContext } from '~/interface/config';+import Noco from '~/Noco';++export default async function getSwaggerJSONV3(+ context: NcContext,+ base: Base,+ models: Model[],+ ncMeta = Noco.ncMeta,+) {+ // base swagger object+ const swaggerObj = {+ ...swaggerBase,+ paths: {},+ components: {+ ...swaggerBase.components,+ schemas: { ...swaggerBase.components.schemas },+ },+ };++ // iterate and populate swagger schema and path for models and views+ for (const model of models) {+ let paths = {};++ const columns = await getSwaggerColumnMetasV3(+ context,+ await model.getColumns(context, ncMeta),+ base,+ ncMeta,+ );++ const views: SwaggerView[] = [];++ for (const view of (await model.getViews(context, false, ncMeta)) || []) {+ if (view.type !== ViewTypes.GRID) continue;+ views.push({+ view,+ columns: await view.getColumns(context, ncMeta),+ });+ }++ // skip mm tables+ if (!model.mm)+ paths = await getPathsV3(context, { model, columns, views }, ncMeta);++ const schemas = await getSchemasV3({ base, model, columns, views }, ncMeta);++ Object.assign(swaggerObj.paths, paths);+ Object.assign(swaggerObj.components.schemas, schemas);+ }++ return swaggerObj;+}++export interface SwaggerView {+ view: View;+ columns: Array<GridViewColumn | GalleryViewColumn | FormViewColumn>;+}diff --git a/packages/nocodb/src/services/api-docs/swaggerV3/swagger-base-v3.json b/packages/nocodb/src/services/api-docs/swaggerV3/swagger-base-v3.jsonnew file mode 100644index 0000000000..c4e8e97ce0--- /dev/null+++ b/packages/nocodb/src/services/api-docs/swaggerV3/swagger-base-v3.json@@ -0,0 +1,129 @@+{+ "openapi": "3.1.0",+ "info": {+ "title": "NocoDB v3",+ "version": "3.0.0",+ "description": "NocoDB API Documentation"+ },+ "servers": [+ {+ "url": "https://app.nocodb.com"+ }+ ],+ "paths": {},+ "components": {+ "schemas": {+ "Paginated": {+ "title": "Paginated",+ "type": "object",+ "properties": {+ "pageSize": {+ "type": "integer"+ },+ "totalRows": {+ "type": "integer"+ },+ "isFirstPage": {+ "type": "boolean"+ },+ "isLastPage": {+ "type": "boolean"+ },+ "page": {+ "type": "number"+ },+ "next": {+ "type": "string",+ "nullable": true,+ "description": "URL to retrieve the next page of records"+ }+ }+ },+ "Attachment": {+ "title": "Attachment",+ "type": "object",+ "properties": {+ "mimetype": {+ "type": "string"+ },+ "size": {+ "type": "integer"+ },+ "title": {+ "type": "string"+ },+ "url": {+ "type": "string"+ },+ "icon": {+ "type": "string"+ }+ }+ },+ "Groupby": {+ "title": "Groupby",+ "type": "object",+ "properties": {+ "count": {+ "type": "number",+ "description": "count"+ },+ "column_name": {+ "type": "string",+ "description": "the value of the given column"+ }+ }+ }+ },+ "securitySchemes": {+ "xcToken": {+ "type": "apiKey",+ "in": "header",+ "name": "xc-token",+ "description": "API token"+ },+ "bearerAuth": {+ "name": "Authorization",+ "type": "http",+ "scheme": "bearer",+ "description": "Bearer token authentication. Use 'Authorization: Bearer <token>' header format. This is an alternative to the xc-token header."+ }+ },+ "responses": {+ "BadRequest": {+ "description": "BadRequest",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "msg": {+ "type": "string",+ "example": "BadRequest [Error]: <ERROR MESSAGE>"+ }+ },+ "required": [+ "msg"+ ]+ },+ "examples": {+ "Example 1": {+ "value": {+ "msg": "BadRequest [Error]: <ERROR MESSAGE>"+ }+ }+ }+ }+ }+ }+ }+ },+ "security": [+ {+ "xcToken": []+ },+ {+ "bearerAuth": []+ }+ ]+}diff --git a/packages/nocodb/src/services/api-docs/swaggerV3/templates/params.ts b/packages/nocodb/src/services/api-docs/swaggerV3/templates/params.tsnew file mode 100644index 0000000000..07bcbe4be2--- /dev/null+++ b/packages/nocodb/src/services/api-docs/swaggerV3/templates/params.ts@@ -0,0 +1,249 @@+import {+ isLinksOrLTAR,+ isSelfLinkCol,+ RelationTypes,+ UITypes,+} from 'nocodb-sdk';+import type { LinkToAnotherRecordColumn } from '~/models';+import type { SwaggerColumn } from '../getSwaggerColumnMetasV3';+import type { SwaggerView } from '~/services/api-docs/swaggerV3/getSwaggerJSONV3';+import type { NcContext } from '~/interface/config';++export const recordIdParam = {+ schema: {+ type: 'string',+ },+ name: 'recordId',+ in: 'path',+ required: true,+ example: 1,+ description:+ 'Primary key of the record you want to read. If the table have composite primary key then combine them by using `___` and pass it as primary key.',+};+export const fieldsParam = {+ schema: {+ type: 'string',+ },+ in: 'query',+ name: 'fields',+ description:+ 'Array of field names or comma separated filed names to include in the response objects. In array syntax pass it like `fields[]=field1&fields[]=field2` or alternately `fields=field1,field2`.',+};+export const sortParam = {+ schema: {+ type: 'string',+ },+ in: 'query',+ name: 'sort',+ description:+ 'Comma separated field names to sort rows, rows will sort in ascending order based on provided columns. To sort in descending order provide `-` prefix along with column name, like `-field`. Example : `sort=field1,-field2`',+};+export const whereParam = {+ schema: {+ type: 'string',+ },+ in: 'query',+ name: 'where',+ description:+ 'This can be used for filtering rows, which accepts complicated where conditions. For more info visit [here](https://docs.nocodb.com/developer-resources/rest-apis#comparison-operators). Example : `where=(field1,eq,value)`',+};+export const limitParam = {+ schema: {+ type: 'number',+ minimum: 1,+ },+ in: 'query',+ name: 'limit',+ description:+ 'The `limit` parameter used for pagination, the response collection size depends on limit value with default value `25` and maximum value `1000`, which can be overridden by environment variables `DB_QUERY_LIMIT_DEFAULT` and `DB_QUERY_LIMIT_MAX` respectively.',+ example: 25,+};+export const offsetParam = {+ schema: {+ type: 'number',+ minimum: 0,+ },+ in: 'query',+ name: 'offset',+ description:+ 'The `offset` parameter used for pagination, the value helps to select collection from a certain index.',+ example: 0,+};++export const shuffleParam = {+ schema: {+ type: 'number',+ minimum: 0,+ maximum: 1,+ },+ in: 'query',+ name: 'shuffle',+ description:+ 'The `shuffle` parameter used for pagination, the response will be shuffled if it is set to 1.',+ example: 0,+};++export const columnNameQueryParam = {+ schema: {+ type: 'string',+ },+ in: 'query',+ name: 'column_name',+ description:+ 'Column name of the column you want to group by, eg. `column_name=column1`',+};++export const linkFieldNameParam = (columns: SwaggerColumn[]) => {+ const linkColumnIds = [];+ const description = [+ '**Links Field Identifier** corresponding to the relation field `Links` established between tables.\n\nLink Columns:',+ ];+ for (const { column } of columns) {+ // Skip non-link columns and non-self-link system columns+ if (!isLinksOrLTAR(column) || (column.system && !isSelfLinkCol(column)))+ continue;++ linkColumnIds.push(column.id);++ description.push(`* ${column.id} - ${column.title}`);+ }++ return {+ schema: {+ type: 'string',+ enum: linkColumnIds,+ },+ name: 'linkFieldId',+ in: 'path',+ required: true,+ description: description.join('\n'),+ };+};+export const viewIdParams = (views: SwaggerView[]) => {+ const viewIds = [];+ const description = [+ 'Allows you to fetch records that are currently visible within a specific view.\n\nViews:',+ ];++ for (const { view } of views) {+ viewIds.push(view.id);+ description.push(+ `* ${view.id} - ${view.is_default ? 'Default view' : view.title}`,+ );+ }++ return {+ schema: {+ type: 'string',+ enum: viewIds,+ },+ description: description.join('\n'),+ name: 'viewId',+ in: 'query',+ required: false,+ };+};++export const referencedRowIdParam = {+ schema: {+ type: 'string',+ },+ name: 'refRowId',+ in: 'path',+ required: true,+};++export const exportTypeParam = {+ schema: {+ type: 'string',+ enum: ['csv', 'excel'],+ },+ name: 'type',+ in: 'path',+ required: true,+};++export const csvExportOffsetParam = {+ schema: {+ type: 'number',+ minimum: 0,+ },+ in: 'query',+ name: 'offset',+ description:+ 'Helps to start export from a certain index. You can get the next set of data offset from previous response header named `nc-export-offset`.',+ example: 0,+};++export const nestedWhereParam = (colName) => ({+ schema: {+ type: 'string',+ },+ in: 'query',+ name: `nested[${colName}][where]`,+ description: `This can be used for filtering rows in nested column \`${colName}\`, which accepts complicated where conditions. For more info visit [here](https://docs.nocodb.com/developer-resources/rest-apis#comparison-operators). Example : \`nested[${colName}][where]=(field1,eq,value)\``,+});++export const nestedFieldParam = (colName) => ({+ schema: {+ type: 'string',+ },+ in: 'query',+ name: `nested[${colName}][fields]`,+ description: `Array of field names or comma separated filed names to include in the in nested column \`${colName}\` result. In array syntax pass it like \`fields[]=field1&fields[]=field2.\`. Example : \`nested[${colName}][fields]=field1,field2\``,+});+export const nestedSortParam = (colName) => ({+ schema: {+ type: 'string',+ },+ in: 'query',+ name: `nested[${colName}][sort]`,+ description: `Comma separated field names to sort rows in nested column \`${colName}\` rows, it will sort in ascending order based on provided columns. To sort in descending order provide \`-\` prefix along with column name, like \`-field\`. Example : \`nested[${colName}][sort]=field1,-field2\``,+});+export const nestedLimitParam = (colName) => ({+ schema: {+ type: 'number',+ minimum: 1,+ },+ in: 'query',+ name: `nested[${colName}][limit]`,+ description: `The \`limit\` parameter used for pagination of nested \`${colName}\` rows, the response collection size depends on limit value and default value is \`25\`.`,+ example: '25',+});+export const nestedOffsetParam = (colName) => ({+ schema: {+ type: 'number',+ minimum: 0,+ },+ in: 'query',+ name: `nested[${colName}][offset]`,+ description: `The \`offset\` parameter used for pagination of nested \`${colName}\` rows, the value helps to select collection from a certain index.`,+ example: 0,+});++export const getNestedParams = async (+ context: NcContext,+ columns: SwaggerColumn[],+): Promise<any[]> => {+ return await columns.reduce(async (paramsArr, { column }) => {+ if (column.uidt === UITypes.LinkToAnotherRecord && !column.system) {+ const colOpt = await column.getColOptions<LinkToAnotherRecordColumn>(+ context,+ );+ if (colOpt.type !== RelationTypes.BELONGS_TO) {+ return [+ ...(await paramsArr),+ nestedWhereParam(column.title),+ nestedOffsetParam(column.title),+ nestedLimitParam(column.title),+ nestedFieldParam(column.title),+ nestedSortParam(column.title),+ ];+ } else {+ return [...(await paramsArr), nestedFieldParam(column.title)];+ }+ }++ return paramsArr;+ }, Promise.resolve([]));+};diff --git a/packages/nocodb/src/services/api-docs/swaggerV3/templates/paths.ts b/packages/nocodb/src/services/api-docs/swaggerV3/templates/paths.tsnew file mode 100644index 0000000000..4f73882f66--- /dev/null+++ b/packages/nocodb/src/services/api-docs/swaggerV3/templates/paths.ts@@ -0,0 +1,462 @@+import { ModelTypes } from 'nocodb-sdk';+import {+ fieldsParam,+ getNestedParams,+ limitParam,+ linkFieldNameParam,+ offsetParam,+ recordIdParam,+ shuffleParam,+ sortParam,+ viewIdParams,+ whereParam,+} from './params';+import type { SwaggerColumn } from '../getSwaggerColumnMetasV3';+import type { SwaggerView } from '~/services/api-docs/swaggerV3/getSwaggerJSONV3';+import type { NcContext } from '~/interface/config';+import { isRelationExist } from '~/services/api-docs/swagger/templates/paths';++export const getModelPaths = async (+ context: NcContext,+ ctx: {+ tableName: string;+ type: ModelTypes;+ columns: SwaggerColumn[];+ tableId: string;+ views: SwaggerView[];+ },+): Promise<{ [path: string]: any }> => ({+ [`/api/v3/data/{baseId}/${ctx.tableId}/records`]: {+ parameters: [+ {+ name: 'baseId',+ in: 'path',+ required: true,+ schema: {+ type: 'string'+ },+ description: 'Base Identifier'+ }+ ],+ get: {+ summary: `${ctx.tableName} list`,+ operationId: `${ctx.tableName.toLowerCase()}-db-table-row-list`,+ description: `List of all rows from ${ctx.tableName} ${ctx.type} and response data fields can be filtered based on query params.`,+ tags: [ctx.tableName],+ parameters: [+ viewIdParams(ctx.views),+ fieldsParam,+ sortParam,+ whereParam,+ limitParam,+ shuffleParam,+ offsetParam,+ ...(await getNestedParams(context, ctx.columns)),+ ],+ responses: {+ '200': {+ description: 'OK',+ content: {+ 'application/json': {+ schema: getPaginatedResponseType(`${ctx.tableName}Response`),+ },+ },+ },+ },+ },+ ...(ctx.type === ModelTypes.TABLE+ ? {+ post: {+ summary: `${ctx.tableName} create`,+ description:+ 'Insert a new row in table by providing a key value pair object where key refers to the column alias. All the required fields should be included with payload excluding `autoincrement` and column with default value.',+ operationId: `${ctx.tableName.toLowerCase()}-create`,+ responses: {+ '200': {+ description: 'OK',+ content: {+ 'application/json': {+ schema: {+ $ref: `#/components/schemas/${ctx.tableName}Response`,+ },+ },+ },+ },+ '400': {+ $ref: '#/components/responses/BadRequest',+ },+ },+ tags: [ctx.tableName],+ requestBody: {+ content: {+ 'application/json': {+ schema: {+ oneOf: [+ {+ $ref: `#/components/schemas/${ctx.tableName}Request`,+ },+ {+ type: 'array',+ items: {+ $ref: `#/components/schemas/${ctx.tableName}Request`,+ },+ },+ ],+ },+ },+ },+ },+ },+ patch: {+ summary: `${ctx.tableName} update`,+ operationId: `${ctx.tableName.toLowerCase()}-update`,+ description:+ 'Partial update row in table by providing a key value pair object where key refers to the column alias. You need to only include columns which you want to update.',+ responses: {+ '200': {+ description: 'OK',+ content: {+ 'application/json': {+ schema: {},+ },+ },+ },+ '400': {+ $ref: '#/components/responses/BadRequest',+ },+ },+ tags: [ctx.tableName],+ requestBody: {+ content: {+ 'application/json': {+ schema: {+ oneOf: [+ {+ $ref: `#/components/schemas/${ctx.tableName}Request`,+ },+ {+ type: 'array',+ items: {+ $ref: `#/components/schemas/${ctx.tableName}Request`,+ },+ },+ ],+ },+ },+ },+ },+ },+ delete: {+ summary: `${ctx.tableName} delete`,+ operationId: `${ctx.tableName.toLowerCase()}-delete`,+ responses: {+ '200': {+ description: 'OK',+ },+ },+ tags: [ctx.tableName],+ description:+ 'Delete a row by using the **primary key** column value.',+ requestBody: {+ content: {+ 'application/json': {+ schema: {+ oneOf: [+ {+ $ref: `#/components/schemas/${ctx.tableName}IdRequest`,+ },+ {+ type: 'array',+ items: {+ $ref: `#/components/schemas/${ctx.tableName}IdRequest`,+ },+ },+ ],+ },+ },+ },+ },+ },+ }+ : {}),+ },+ [`/api/v3/data/{baseId}/${ctx.tableId}/records/{recordId}`]: {+ parameters: [+ {+ name: 'baseId',+ in: 'path',+ required: true,+ schema: {+ type: 'string'+ },+ description: 'Base Identifier'+ },+ recordIdParam,+ fieldsParam+ ],+ get: {+ summary: `${ctx.tableName} read`,+ description: 'Read a row data by using the **primary key** column value.',+ operationId: `${ctx.tableName.toLowerCase()}-read`,+ tags: [ctx.tableName],+ responses: {+ '201': {+ description: 'Created',+ content: {+ 'application/json': {+ schema: {+ $ref: `#/components/schemas/${ctx.tableName}Response`,+ },+ },+ },+ },+ },+ },+ },+ [`/api/v3/data/{baseId}/${ctx.tableId}/records/count`]: {+ parameters: [+ {+ name: 'baseId',+ in: 'path',+ required: true,+ schema: {+ type: 'string'+ },+ description: 'Base Identifier'+ },+ ...viewIdParams(ctx.views)+ ],+ get: {+ summary: `${ctx.tableName} count`,+ operationId: `${ctx.tableName.toLowerCase()}-count`,+ description: 'Get rows count of a table by applying optional filters.',+ tags: [ctx.tableName],+ parameters: [whereParam],+ responses: {+ '200': {+ description: 'OK',+ content: {+ 'application/json': {+ schema: {+ type: 'object',+ properties: {+ count: {+ type: 'number',+ },+ },+ required: ['count'],+ },+ examples: {+ 'Example 1': {+ value: {+ count: 3,+ },+ },+ },+ },+ },+ },+ '400': {+ $ref: '#/components/responses/BadRequest',+ },+ },+ },+ },++ ...(isRelationExist(ctx.columns)+ ? {+ [`/api/v3/data/{baseId}/${ctx.tableId}/links/{linkFieldId}/records/{recordId}`]:+ {+ parameters: [+ {+ name: 'baseId',+ in: 'path',+ required: true,+ schema: {+ type: 'string'+ },+ description: 'Base Identifier'+ },+ linkFieldNameParam(ctx.columns),+ recordIdParam+ ],+ get: {+ summary: 'Link Records list',+ operationId: `${ctx.tableName.toLowerCase()}-nested-list`,+ description:+ 'This API endpoint allows you to retrieve list of linked records for a specific `Link field` and `Record ID`. The response is an array of objects containing Primary Key and its corresponding display value.',+ tags: [ctx.tableName],+ parameters: [+ fieldsParam,+ sortParam,+ whereParam,+ limitParam,+ offsetParam,+ ],+ responses: {+ '200': {+ description: 'OK',+ content: {+ 'application/json': {+ schema: {+ type: 'object',+ properties: {+ list: {+ type: 'array',+ description: 'List of data objects',+ items: {+ type: 'object',+ },+ },+ pageInfo: {+ $ref: '#/components/schemas/Paginated',+ description: 'Paginated Info',+ },+ },+ required: ['list', 'pageInfo'],+ },+ },+ },+ },+ '400': {+ $ref: '#/components/responses/BadRequest',+ },+ },+ },+ post: {+ summary: 'Link Records',+ operationId: `${ctx.tableName.toLowerCase()}-nested-link`,+ responses: {+ '200': {+ description: 'OK',+ content: {+ 'application/json': {+ schema: {},+ examples: {+ 'Example 1': {+ value: true,+ },+ },+ },+ },+ },+ '400': {+ $ref: '#/components/responses/BadRequest',+ },+ },+ tags: [ctx.tableName],+ requestBody: {+ content: {+ 'application/json': {+ schema: {+ oneOf: [+ {+ type: 'object',+ },+ {+ type: 'array',+ items: {+ type: 'object',+ },+ },+ ],+ },+ examples: {+ 'Example 1': {+ value: [+ {+ Id: 4,+ },+ {+ Id: 5,+ },+ ],+ },+ 'Example 2': {+ value: {+ Id: 4,+ },+ },+ },+ },+ },+ },+ description:+ 'This API endpoint allows you to link records to a specific `Link field` and `Record ID`. The request payload is an array of record-ids from the adjacent table for linking purposes. Note that any existing links, if present, will be unaffected during this operation.',+ parameters: [recordIdParam],+ },+ delete: {+ summary: 'Unlink Records',+ operationId: `${ctx.tableName.toLowerCase()}-nested-unlink`,+ responses: {+ '200': {+ description: 'OK',+ content: {+ 'application/json': {+ schema: {},+ examples: {+ 'Example 1': {+ value: true,+ },+ },+ },+ },+ },+ '400': {+ $ref: '#/components/responses/BadRequest',+ },+ },+ tags: [ctx.tableName],+ requestBody: {+ content: {+ 'application/json': {+ schema: {+ oneOf: [+ {+ type: 'array',+ items: {+ type: 'object',+ },+ },+ ],+ },+ examples: {+ 'Example 1': {+ value: [+ {+ Id: 1,+ },+ {+ Id: 2,+ },+ ],+ },+ },+ },+ },+ },+ description:+ 'This API endpoint allows you to unlink records from a specific `Link field` and `Record ID`. The request payload is an array of record-ids from the adjacent table for unlinking purposes. Note that, \n- duplicated record-ids will be ignored.\n- non-existent record-ids will be ignored.',+ parameters: [recordIdParam],+ },+ },+ }+ : {}),+});++function getPaginatedResponseType(type: string) {+ return {+ type: 'object',+ properties: {+ list: {+ type: 'array',+ items: {+ $ref: `#/components/schemas/${type}`,+ },+ },+ pageInfo: {+ $ref: `#/components/schemas/Paginated`,+ },+ },+ };+}diff --git a/packages/nocodb/src/services/api-docs/swaggerV3/templates/schemas.ts b/packages/nocodb/src/services/api-docs/swaggerV3/templates/schemas.tsnew file mode 100644index 0000000000..1a91ac9a59--- /dev/null+++ b/packages/nocodb/src/services/api-docs/swaggerV3/templates/schemas.ts@@ -0,0 +1,110 @@+import { isSystemColumn } from 'nocodb-sdk';+import type { SwaggerColumn } from '../getSwaggerColumnMetasV3';++export const getModelSchemas = (ctx: {+ tableName: string;+ orgs: string;+ baseName: string;+ columns: Array<SwaggerColumn>;+}) => ({+ [`${ctx.tableName}Response`]: {+ title: `${ctx.tableName} Response`,+ type: 'object',+ description: '',+ 'x-internal': false,+ properties: {+ ...(ctx.columns?.reduce(+ (colsObj, { title, virtual, column, ...fieldProps }) => ({+ ...colsObj,+ ...(column.system+ ? {}+ : {+ [title]: fieldProps,+ }),+ }),+ {},+ ) || {}),+ },+ },+ [`${ctx.tableName}Request`]: {+ title: `${ctx.tableName} Request`,+ type: 'object',+ description: '',+ 'x-internal': false,+ properties: {+ ...(ctx.columns?.reduce(+ (colsObj, { title, virtual, column, ...fieldProps }) => ({+ ...colsObj,+ ...(virtual || isSystemColumn(column) || column.ai || column.meta?.ag+ ? {}+ : {+ [title]: fieldProps,+ }),+ }),+ {},+ ) || {}),+ },+ },+ [`${ctx.tableName}IdRequest`]: {+ title: `${ctx.tableName} Id Request`,+ type: 'object',+ description: '',+ 'x-internal': false,+ properties: {+ ...(ctx.columns?.reduce(+ (colsObj, { title, virtual, column, ...fieldProps }) => ({+ ...colsObj,+ ...(column.pk+ ? {+ [title]: fieldProps,+ }+ : {}),+ }),+ {},+ ) || {}),+ },+ },+});++export const getViewSchemas = (ctx: {+ tableName: string;+ viewName: string;+ orgs: string;+ baseName: string;+ columns: Array<SwaggerColumn>;+}) => ({+ [`${ctx.tableName}${ctx.viewName}GridResponse`]: {+ title: `${ctx.tableName} : ${ctx.viewName} Response`,+ type: 'object',+ description: '',+ 'x-internal': false,+ properties: {+ ...(ctx.columns?.reduce(+ (colsObj, { title, virtual, column, ...fieldProps }) => ({+ ...colsObj,+ [title]: fieldProps,+ }),+ {},+ ) || {}),+ },+ },+ [`${ctx.tableName}${ctx.viewName}GridRequest`]: {+ title: `${ctx.tableName} : ${ctx.viewName} Request`,+ type: 'object',+ description: '',+ 'x-internal': false,+ properties: {+ ...(ctx.columns?.reduce(+ (colsObj, { title, virtual, column, ...fieldProps }) => ({+ ...colsObj,+ ...(virtual+ ? {}+ : {+ [title]: fieldProps,+ }),+ }),+ {},+ ) || {}),+ },+ },+});