Using Repositories

Now let’s refactor our code and use Repository instead of EntityManager.Each entity has its own repository which handles all operations with its entity.When you deal with entities a lot, Repositories are more convenient to use than EntityManagers:

  1. import {createConnection} from "typeorm";
  2. import {Photo} from "./entity/Photo";
  3. createConnection(/*...*/).then(async connection => {
  4. let photo = new Photo();
  5. photo.name = "Me and Bears";
  6. photo.description = "I am near polar bears";
  7. photo.filename = "photo-with-bears.jpg";
  8. photo.views = 1;
  9. photo.isPublished = true;
  10. let photoRepository = connection.getRepository(Photo);
  11. await photoRepository.save(photo);
  12. console.log("Photo has been saved");
  13. let savedPhotos = await photoRepository.find();
  14. console.log("All photos from the db: ", savedPhotos);
  15. }).catch(error => console.log(error));

Learn more about Repository here.