本文整理汇总了TypeScript中typeorm.Connection类的典型用法代码示例。如果您正苦于以下问题:TypeScript Connection类的具体用法?TypeScript Connection怎么用?TypeScript Connection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Connection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: async
.get('/:id', async (req, res) => {
vary(res, 'Accept-Language');
const connection: Connection = req.app.locals.connection;
const locale: Language = req.app.locals.locale;
const photo = await connection
.getRepository(Photo)
.createQueryBuilder('photo')
.innerJoinAndSelect("photo.translations", "translation", "translation.language = :locale", { locale })
.select([
"photo.id",
"photo.src",
"photo.views",
"photo.datetime",
"photo.group",
"photo.width",
"photo.height",
"translation.field",
"translation.value",
])
.where("photo.id = :id", { id: req.params.id })
.andWhere("photo.hidden = :hidden", { hidden: false })
.getOne();
await connection.getRepository(Photo).increment(photo, 'views', 1);
res.send(photoDTO(photo));
})
示例2: async
.get('/:alias', async (req, res) => {
vary(res, 'Accept-Language');
res.set('Cache-Control', `public, max-age=${60 * 60 * 24 * 30}`)
const connection: Connection = req.app.locals.connection;
const locale: Language = req.app.locals.locale;
const page = await connection
.getRepository(Page)
.createQueryBuilder('page')
.leftJoinAndSelect("page.translations", "translation", "translation.language = :locale", { locale })
.select([
"page.alias",
"translation.field",
"translation.value",
])
.where('page.alias = :alias', { alias: req.params.alias })
.andWhere("page.hidden = :hidden", { hidden: false })
.getOne();
if (!page) {
res.sendStatus(404);
}
res.send(pageDTO(page));
});
示例3: async
.get('/', async (req, res) => {
vary(res, 'Accept-Language');
res.set('Cache-Control', `public, max-age=${60 * 60 * 24 * 30}`);
const connection: Connection = req.app.locals.connection;
const locale: Language = req.app.locals.locale;
const categories = await connection
.getRepository(Category)
.createQueryBuilder('category')
.leftJoinAndSelect("category.translations", "translation",
"translation.language = :locale AND translation.field = :field", { locale, field: "title" })
.leftJoinAndSelect("category.featured", "featured")
.leftJoinAndSelect("category.parent", "parent")
.select([
"category.name",
"category.date",
"translation.field",
"translation.value",
"parent.name",
"featured.src",
])
.where("category.hidden = :hidden", { hidden: false })
.getMany();
res.send(unnest(categories).map(categoryDTO));
})
示例4: async
.get('/', async (req, res) => {
vary(res, 'Accept-Language');
res.set('Cache-Control', `public, max-age=${60 * 60 * 24}`);
const connection: Connection = req.app.locals.connection;
const photos = await connection
.getRepository(Photo)
.createQueryBuilder('photo')
.innerJoinAndSelect("photo.categories", "category", "category.name = :name", { name: req.params.category })
.select([
"photo.id",
"photo.src",
"photo.views",
"photo.datetime",
"photo.group",
])
.where("photo.hidden = :hidden", { hidden: false })
.andWhere("category.hidden = :hidden", { hidden: false })
.orderBy('photo.datetime')
.getMany();
res.send(photos);
})
示例5: describe
describe('WelcomeService', () => {
let connection: Connection;
let welcomeService: WelcomeService;
beforeAll(async () => {
const module = await createTestModule({
imports: [DtoTransformerModule],
providers: [WelcomeService]
});
connection = module.get<Connection>(Connection);
welcomeService = module.get<WelcomeService>(WelcomeService);
});
beforeEach(async () => {
await createTestData();
});
afterAll(async () => {
await connection.close();
});
describe('generateGreeting', () => {
it('should generate greeting', async () => {
expect(welcomeService.generateGreeting('John Doe')).toBe('Hello, John Doe');
});
});
describe('findAllFolders', () => {
it('should find all folders', async () => {
const loadedFolders = await welcomeService.findAllFolders();
expect(loadedFolders).toBeArrayOfSize(8);
expect(loadedFolders[0].id).toBeGreaterThanOrEqual(1);
expect(loadedFolders[0].name).toBe('C:');
expect(loadedFolders[0].dateAdded).toBeValidDate();
expect(loadedFolders[0].children).toBeUndefined();
expect(loadedFolders[0].parent).toBeUndefined();
});
});
});
示例6: describe
describe('SERVER ORM: ORMConnectionProvider', () => {
let container: Container;
let connection: Connection;
beforeEach(async () => {
container = new Container();
container
.bind<ConnectionOptions>(registry.ORMConnectionOptions)
.toConstantValue({
autoSchemaSync: true,
type: 'sqlite',
database: ':memory:'
});
container
.bind<interfaces.Provider<Connection>>(registry.ORMConnectionProvider)
.toProvider<Connection>(connectionProvider);
connection = (await container.get<interfaces.Provider<Connection>>(
registry.ORMConnectionProvider
)()) as Connection;
});
afterEach(async () => {
await connection.close();
container.unbind(registry.ORMConnectionOptions);
container.unbind(registry.ORMConnection);
});
it('should be connected to database', () => {
expect(connection).toBeDefined();
expect(connection.isConnected).toBeTruthy();
});
it('should return the same connection when one already exists', async () => {
const newConnection = (await container.get<interfaces.Provider<Connection>>(
registry.ORMConnectionProvider
)()) as Connection;
expect(connection).toBe(newConnection);
});
});
示例7: describe
describe('WelcomeController', () => {
let connection: Connection;
let welcomeController: WelcomeController;
let welcomeService: WelcomeService;
beforeAll(async () => {
const module = await createTestModule({
imports: [DtoTransformerModule],
controllers: [WelcomeController],
providers: [WelcomeService]
});
connection = module.get<Connection>(Connection);
welcomeController = module.get<WelcomeController>(WelcomeController);
welcomeService = module.get<WelcomeService>(WelcomeService);
await createTestData();
});
beforeEach(async () => {
await createTestData();
});
afterAll(async () => {
await connection.close();
});
describe('findAllFolders', () => {
it('should return an array of folders', async () => {
jest.spyOn(welcomeService, 'findAllFolders').mockImplementation(() => [new Folder()]);
const result = await welcomeController.test();
expect(result).toBeDefined();
expect(result).toBeArrayOfSize(1);
});
});
});
示例8: describe
describe('SERVER CONTROLLERS: CardSetController', () => {
let container: Container;
let mockSettingsService: SettingsServiceAttributes;
let mockLogger: winston.LoggerInstance;
let connection: Connection;
let app: express.Application;
beforeEach(async () => {
container = new Container();
container.load(ormModule);
// Services
container
.bind<SettingsServiceAttributes>(registry.SettingsService)
.to(MockSettingsService)
.inSingletonScope();
mockSettingsService = container.get<SettingsServiceAttributes>(
registry.SettingsService
);
mockSettingsService.loggerTransports = [
new winston.transports.Console({
silent: true
})
];
mockLogger = new winston.Logger();
const loggerFactory: interfaces.FactoryCreator<winston.LoggerInstance> = (
context: interfaces.Context
) => {
return () => {
return mockLogger;
};
};
container
.bind<interfaces.Factory<winston.LoggerInstance>>(registry.LoggerFactory)
.toFactory(loggerFactory);
// ORM
container
.bind<ConnectionOptions>(registry.ORMConnectionOptions)
.toConstantValue({
autoSchemaSync: true,
type: 'sqlite',
database: ':memory:'
});
connection = (await container.get<interfaces.Provider<Connection>>(
registry.ORMConnectionProvider
)()) as Connection;
// Express configs
container
.bind<CardSetControllerAttributes>(CardSetController)
.toSelf();
app = express();
useContainer(container);
useExpressServer(app, {
routePrefix: '/api',
controllers: [CardSetController],
development: true
});
});
afterEach(async () => {
await connection.close();
});
it('should be defined', () => {
expect(app).toBeDefined();
});
describe('GET', () => {
it('should respond successfully', async () => {
/* tslint:disable:no-any */
const cardSetRepositoryFind = jest
.spyOn(connection.getRepository('CardSet'), 'find')
.mockImplementation(async (entity: any): Promise<any> =>
Promise.resolve([])
);
/* tslint:enable:no-any */
await supertest(app).get('/api/cardSets').expect(200).then(response => {
expect(response).toBeDefined();
expect(response.body.cardSets).toBeDefined();
expect(Array.isArray(response.body.cardSets)).toBe(true);
expect(response.body.cardSets.length).toBe(0);
expect(cardSetRepositoryFind).toHaveBeenCalledTimes(1);
});
});
describe('ORM Integration', () => {
it('should return DBError', async () => {
const error = new Error(
`${ORMErrorNameEnum.AlreadyHasActiveConnectionError}: Some orm error.`
);
error.name = ORMErrorNameEnum.AlreadyHasActiveConnectionError;
/* tslint:disable:no-any */
const cardSetRepositoryFind = jest
.spyOn(connection.getRepository('CardSet'), 'find')
.mockImplementation(async (entity: any): Promise<any> =>
Promise.reject(error)
);
/* tslint:enable:no-any */
//.........这里部分代码省略.........
示例9: describe
describe('ImageController', () => {
let connection: Connection;
let imageController: ImageController;
let imageService: ImageService;
let dummyImage: ImageDto;
beforeAll(async () => {
const module = await createTestModule({
imports: [DtoTransformerModule],
controllers: [ImageController],
providers: [
ImageService,
FolderService,
PathHelperService
]
});
connection = module.get<Connection>(Connection);
imageController = module.get<ImageController>(ImageController);
imageService = module.get<ImageService>(ImageService);
dummyImage = {
id: 42,
name: 'dummy',
extension: 'jpg',
absolutePath: 'C:\\foo\\bar\\dummy.jpg',
parentFolder: {
id: 43,
name: 'bar',
absolutePath: 'C:\\foo\\bar'
} as FolderDto
};
});
beforeEach(async () => {
await createTestData();
});
afterAll(async () => {
await connection.close();
});
describe('create', () => {
it('should return an image', async () => {
jest.spyOn(imageService, 'create').mockImplementation(() => dummyImage);
const result = await imageController.create({ foo: 'bar' });
expect(result).toBeDefined();
expect(result).toContainKeys(['id', 'name', 'extension', 'absolutePath']);
});
});
describe('createByPath', () => {
it('should return an image', async () => {
jest.spyOn(imageService, 'create').mockImplementation(() => dummyImage);
const result = await imageController.createByPath({
absolutePath: 'C:\\foo\\bar\\dummy.jpg',
name: 'dummy',
extension: 'jpg'
});
expect(result).toBeDefined();
expect(result).toContainKeys(['id', 'name', 'extension', 'absolutePath']);
});
});
describe('findAll', () => {
it('should return an array of images', async () => {
jest.spyOn(imageService, 'findAll').mockImplementation(() => [dummyImage, dummyImage]);
const result = await imageController.findAll();
expect(result).toBeDefined();
expect(result).toBeArrayOfSize(2);
expect(result[0]).toContainKeys(['id', 'name', 'extension', 'absolutePath']);
expect(result[1]).toContainKeys(['id', 'name', 'extension', 'absolutePath']);
});
});
describe('findOne', () => {
it('should return an image', async () => {
jest.spyOn(imageService, 'findOne').mockImplementation(() => dummyImage);
const result = await imageController.findOne(42);
expect(result).toBeDefined();
expect(result).toContainKeys(['id', 'name', 'extension', 'absolutePath']);
});
});
describe('update', () => {
it('should return an UpdateResult', async () => {
jest.spyOn(imageService, 'update').mockImplementation(() => new UpdateResult());
const result = await imageController.update(42, { foo: 'bar' });
expect(result).toBeDefined();
expect(result instanceof UpdateResult).toBeTrue();
});
});
describe('remove', () => {
it('should return an image', async () => {
//.........这里部分代码省略.........
示例10: describe
describe('FolderService', () => {
let connection: Connection;
let folderService: FolderService;
let imageService: ImageService;
beforeAll(async () => {
const module = await createTestModule({
imports: [DtoTransformerModule],
providers: [FolderService, PathHelperService, ImageService]
});
connection = module.get<Connection>(Connection);
folderService = module.get<FolderService>(FolderService);
imageService = module.get<ImageService>(ImageService);
});
beforeEach(async () => {
await createTestData();
});
afterAll(async () => {
await connection.close();
});
describe('create', () => {
it('should save a folder', async () => {
const f6 = await folderService.findOneByName('F6');
const result = await folderService.create({
name: 'dummy-folder',
parent: f6
});
expect(result).toBeDefined();
expect(result.id).toBeGreaterThan(1);
expect(result.name).toBe('dummy-folder');
expect(result.dateAdded).toBeValidDate();
});
});
describe('findOne', () => {
it('should find folder by id', async () => {
const result = await folderService.findOne(3, true);
expect(result).toBeDefined();
expect(result.id).toBe(3);
expect(result.name).toBe('F2');
expect(result.dateAdded).toBeValidDate();
expect(result.parent.name).toBe('C:');
expect(result.children).toBeArrayOfSize(1);
expect(result.children[0].name).toBe('F3');
});
});
describe('findOneByName', () => {
it('should find folder by name', async () => {
const result = await folderService.findOneByName('F2', true);
expect(result).toBeDefined();
expect(result.id).toBe(3);
expect(result.name).toBe('F2');
expect(result.dateAdded).toBeValidDate();
expect(result.parent.name).toBe('C:');
expect(result.children).toBeArrayOfSize(1);
expect(result.children[0].name).toBe('F3');
});
});
describe('findDirectDescendantsByFolderId', () => {
it('should find direct descendants folders by id', async () => {
const result = await folderService.findDirectDescendantsByFolderId(1);
expect(result).toBeDefined();
expect(result).toBeArrayOfSize(2);
expect(result.map(folder => folder.name)).toEqual(['F1', 'F2']);
});
});
describe('findDirectDescendantsByFolder', () => {
it('should find direct descendants folders by folder', async () => {
const c = await folderService.findOneByName('C:');
const result = await folderService.findDirectDescendantsByFolder(c);
expect(result).toBeDefined();
expect(result).toBeArrayOfSize(2);
expect(result.map(folder => folder.name)).toEqual(['F1', 'F2']);
});
});
describe('findRootFolders', () => {
it('should find folders without parent (root folders)', async () => {
const result = await folderService.findRootFolders();
expect(result).toBeDefined();
expect(result).toBeArrayOfSize(2);
expect(result.map(folder => folder.name)).toEqual(['C:', 'D:']);
});
});
describe('findAll', () => {
it('should find all folders', async () => {
const result = await folderService.findAll();
//.........这里部分代码省略.........
示例11: describe
describe('DictionaryEntryResolver', () => {
let dictionaryEntryResolver: DictionaryEntryResolver;
let connection: Connection;
beforeEach(async () => {
const testModule: TestingModule = await Test.createTestingModule({
providers: [
...databaseProviders,
...dictionaryEntryProviders,
DictinaryEntryService,
DictionaryEntryResolver,
AuthGuard,
{
provide: Types.CONFIG,
useValue: {
mongoConnectionUri: `mongodb://localhost:27017/TEST_${uuidv4()}`,
secureApiToken: 'test_token',
},
},
],
}).compile();
connection = await prepareDatabaseScenario(testModule, [
createDataFor<DictionaryEntryEntity>(DictionaryEntryEntity, [
{ japanese: 'inu', english: 'dog' },
{ japanese: 'neko', english: 'cat' },
]),
]);
dictionaryEntryResolver = testModule.get<DictionaryEntryResolver>(
DictionaryEntryResolver,
);
});
afterEach(async () => {
await connection.dropDatabase();
await connection.close();
});
describe('search', () => {
it('should return entries containing "dog', async () => {
const searchResults = await dictionaryEntryResolver.search('dog');
expect(searchResults).toMatchObject([
{ japanese: 'inu', english: 'dog' },
]);
});
});
describe('add entry', () => {
it('should add new entry', async () => {
const response = await dictionaryEntryResolver.addDictionaryEntry({
japanese: 'kame',
english: 'turtle',
});
expect(response).toMatchObject({
code: 201,
message: 'Dictionary entry succesfully added.',
isSuccessful: true,
dictionaryEntry: {
japanese: 'kame',
english: 'turtle',
},
});
const addedEntry = await dictionaryEntryResolver.dictionaryEntry(
response.dictionaryEntry.id,
);
expect(addedEntry).toMatchObject({ japanese: 'kame', english: 'turtle' });
});
});
});
示例12:
useFactory: (connection: Connection) =>
connection.getRepository(DictionaryEntryEntity),
示例13: afterEach
afterEach(async () => {
await connection.close();
container.unbind(registry.ORMConnectionOptions);
container.unbind(registry.ORMConnection);
});
示例14: describe
describe('FolderController', () => {
let connection: Connection;
let folderController: FolderController;
let folderService: FolderService;
let dummyFolder: FolderDto;
beforeAll(async () => {
const module = await createTestModule({
imports: [DtoTransformerModule],
controllers: [FolderController],
providers: [FolderService, PathHelperService]
});
connection = module.get<Connection>(Connection);
folderController = module.get<FolderController>(FolderController);
folderService = module.get<FolderService>(FolderService);
dummyFolder = new FolderDto();
dummyFolder.id = 43;
dummyFolder.name = 'bar';
dummyFolder.absolutePath = 'C:\\foo\\bar';
});
beforeEach(async () => {
await createTestData();
});
afterAll(async () => {
await connection.close();
});
describe('create', () => {
it('should return a folder', async () => {
jest.spyOn(folderService, 'create').mockImplementation(() => dummyFolder);
const result = await folderController.create({ foo: 'bar' });
expect(result).toBeDefined();
expect(result).toContainKeys(['id', 'name', 'absolutePath']);
});
});
describe('createByPath', () => {
it('should return a folder', async () => {
jest.spyOn(folderService, 'createFolderByPath').mockImplementation(() => dummyFolder);
const result: FolderDto = await folderController.createByPath({ path: 'some/path' });
expect(result).toBeDefined();
expect(result).toContainKeys(['id', 'name', 'absolutePath']);
});
});
describe('findAll', () => {
it('should return an array of folders', async () => {
jest.spyOn(folderService, 'findAll').mockImplementation(() => [dummyFolder, dummyFolder]);
const result = await folderController.findAll();
expect(result).toBeDefined();
expect(result).toBeArrayOfSize(2);
expect(result[0]).toContainKeys(['id', 'name', 'absolutePath']);
expect(result[1]).toContainKeys(['id', 'name', 'absolutePath']);
});
});
describe('findOne', () => {
it('should return a folder', async () => {
jest.spyOn(folderService, 'findOne').mockImplementation(() => dummyFolder);
const result = await folderController.findOne(42);
expect(result).toBeDefined();
expect(result).toContainKeys(['id', 'name', 'absolutePath']);
});
});
describe('update', () => {
it('should return an UpdateResult', async () => {
jest.spyOn(folderService, 'update').mockImplementation(() => new UpdateResult());
const result = await folderController.update(42, { foo: 'bar' });
expect(result).toBeDefined();
expect(result instanceof UpdateResult).toBeTrue();
});
});
describe('remove', () => {
it('should return a folder', async () => {
jest.spyOn(folderService, 'remove').mockImplementation(() => dummyFolder);
const result = await folderController.remove(42);
expect(result).toBeUndefined();
});
});
});
示例15: Close
public Close(): void {
if (!this.connection) {
return;
}
this.server.Log('Stopping database...');
this.connection.close();
this.connection = undefined;
this.config = undefined;
this.server.Log('Database connection closed.');
this.server = undefined;
}