Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: dynamic models, repositories and controllers at runtime #5564

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 23 additions & 35 deletions packages/repository/src/repositories/legacy-juggler-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,43 +6,14 @@
import {Getter} from '@loopback/context';
import assert from 'assert';
import legacy from 'loopback-datasource-juggler';
import {
AnyObject,
Command,
Count,
DataObject,
DeepPartial,
NamedParameters,
Options,
PositionalParameters,
} from '../common-types';
import {AnyObject, Command, Count, DataObject, DeepPartial, NamedParameters, Options, PositionalParameters} from '../common-types';
import {EntityNotFoundError} from '../errors';
import {
Entity,
Model,
PropertyType,
rejectNavigationalPropertiesInData,
} from '../model';
import {Entity, Model, ModelDefinition, PropertyType, rejectNavigationalPropertiesInData} from '../model';
import {Filter, FilterExcludingWhere, Inclusion, Where} from '../query';
import {
BelongsToAccessor,
BelongsToDefinition,
createBelongsToAccessor,
createHasManyRepositoryFactory,
createHasOneRepositoryFactory,
HasManyDefinition,
HasManyRepositoryFactory,
HasOneDefinition,
HasOneRepositoryFactory,
includeRelatedModels,
InclusionResolver,
} from '../relations';
import {BelongsToAccessor, BelongsToDefinition, createBelongsToAccessor, createHasManyRepositoryFactory, createHasOneRepositoryFactory, HasManyDefinition, HasManyRepositoryFactory, HasOneDefinition, HasOneRepositoryFactory, includeRelatedModels, InclusionResolver} from '../relations';
import {IsolationLevel, Transaction} from '../transaction';
import {isTypeResolver, resolveType} from '../type-resolver';
import {
EntityCrudRepository,
TransactionalEntityRepository,
} from './repository';
import {EntityCrudRepository, TransactionalEntityRepository} from './repository';

export namespace juggler {
/* eslint-disable @typescript-eslint/no-unused-vars */
Expand Down Expand Up @@ -105,7 +76,7 @@ export class DefaultCrudRepository<
T extends Entity,
ID,
Relations extends object = {}
> implements EntityCrudRepository<T, ID, Relations> {
> implements EntityCrudRepository<T, ID, Relations> {
modelClass: juggler.PersistedModelClass;

public readonly inclusionResolvers: Map<
Expand Down Expand Up @@ -625,7 +596,7 @@ export class DefaultTransactionalRepository<
T extends Entity,
ID,
Relations extends object = {}
> extends DefaultCrudRepository<T, ID, Relations>
> extends DefaultCrudRepository<T, ID, Relations>
implements TransactionalEntityRepository<T, ID, Relations> {
async beginTransaction(
options?: IsolationLevel | Options,
Expand All @@ -637,3 +608,20 @@ export class DefaultTransactionalRepository<
return (await this.dataSource.beginTransaction(dsOptions)) as Transaction;
}
}

export type SchemaDefinition = {
name: string,
properties: {[prop: string]: string},
options: {[prop: string]: string},
}

export function discoverModelDefinition(schema: SchemaDefinition): ModelDefinition {
return new ModelDefinition({
name: schema.name,
// TODO: convert from juggler/LB3 style to LB4
// For example, we need to transform array-type definitions from
// {type: ['string']} to {type: 'array', itemType: 'string'}
properties: schema.properties,
settings: schema.options,
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,14 @@
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {ApplicationConfig} from '@loopback/core/src';
import {anOperationSpec} from '@loopback/openapi-spec-builder';
import {RepositoryMixin} from '@loopback/repository';
import {Client, createRestAppClient, expect} from '@loopback/testlab';
import express, {Request, Response} from 'express';
import fs from 'fs';
import path from 'path';
import {
get,
RestApplication,
RestServer,
RestServerConfig,
RouterSpec,
} from '../..';
import {get, RestApplication, RestServer, RestServerConfig, RouterSpec} from '../..';

const ASSETS = path.resolve(__dirname, '../../../fixtures/assets');

Expand Down Expand Up @@ -271,8 +267,29 @@ describe('RestApplication (integration)', () => {
await client.get('/api/dogs/poodle').expect(200, 'Poodle!');
});

it('adds dynamic routes from models at runtime', async () => {
const app = new DynamicApp();
await app.start();
client = createRestAppClient(app);
// No DummyController is present
await client.get('/books/1').expect(404);
// Add DummyController after server.start
await app.dynamic({
name: 'dynamo',
connector: 'memory'
});
// Now /html is available
await client.get('/books/1').expect(200);
});

function givenApplication(options?: {rest: RestServerConfig}) {
options = options ?? {rest: {port: 0, host: '127.0.0.1'}};
restApp = new RestApplication(options);
}

class DynamicApp extends RepositoryMixin(RestApplication) {
constructor(options: ApplicationConfig = {}) {
super(options);
}
}
});
73 changes: 73 additions & 0 deletions packages/rest/src/mixins/dynamic.mixin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Copyright IBM Corp. 2018,2020. All Rights Reserved.
// Node module: @loopback/repository
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {Application, MixinTarget} from '@loopback/core';
import {juggler} from '@loopback/repository/src';
import debugFactory from 'debug';

const debug = debugFactory('loopback:rest:mixin');

/**
* Interface for classes with `new` operator.
*/
export interface Class<T> {
// new MyClass(...args) ==> T
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new(...args: any[]): T;
}

/* eslint-enable @typescript-eslint/no-unused-vars */

/**
* A mixin class for Application that creates a .dynamic()
* function to build models, repositories and controllers dynamically at runtime.
*
* @example
* ```ts
* class MyApplication extends DynamicMixin(Application) {}
*
* const app = new MyApplication();
* await app.start();
* app.dynamic(
* {
* name: 'dynamo',
* connector: 'loopback-connector-mongodb',
* connectionString: 'mongodb://sysop:moon@localhost/records',
* restApi: false,
* }
* );
* ```
*
*/
export function DynamicMixin<T extends MixinTarget<Application>>(
superClass: T,
) {
return class extends superClass {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async dynamic(options: DynamicOptions) {
const {name, connector, connectionString} = options;
if (!connectionString && connector !== 'memory') {
throw new Error(`Connection string is required for ${connector}`);
}
// Enable REST API by default
const restApi = ('restApi' in options) ? options.restApi : true;

const ds = new juggler.DataSource({
name: name,
connector: require(connector),
url: connectionString,
});
await ds.connect();
this.dataSource(ds, name);
}
};
}

export type DynamicOptions = {
name: string;
connector: string;
connectionString?: string;
restApi: boolean;
}
7 changes: 7 additions & 0 deletions packages/rest/src/mixins/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Copyright IBM Corp. 2018,2020. All Rights Reserved.
// Node module: @loopback/service-proxy
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

export * from './dynamic.mixin';