Giter Club home page Giter Club logo

typescript-sequelize-example's Introduction

So you want to use types with Sequelize?

How to use Typescript with Sequelize

This repo shows how to use Sequelize v4 with Typescript, including how to set up associations.

You can use tags in this repo to follow along with the accompnaying article, which is found here.

The automated script for generating ModelInstance definitions is found here.

Usage

You can run the web server with yarn install && yarn start. The server is launched on port 3000. You can access paths via your browser, or, by using a HTTP client like Postman.

App Structure

Inside src/app.ts, we launch the server and set up lots of example paths to demonstrate Sequelize+Typescript in action. The model definitions are in src/models/. Some types we define to help us get better type inference across our project when using Sequelize+Typescript are found in src/typings.

Setting up your database

The database connection config passed into Sequelize is stored in src/config/sequelizeConfig.json. It currently connects to a Postgres database on localhost called tutorial, with user postgres and no password. You may wish to change this. You probably will also need to create a database yourself. You don't have to use Postgres; Sequelize is database agnostic.

typescript-sequelize-example's People

Contributors

ahmerb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

typescript-sequelize-example's Issues

'/seed/user' not working.

Running the app creates all the tables successfully.

If I post to localhost:3000/seed/user I can see in pgAdmin that the user John Doe has been created.

1 "John Doe" "2018-10-08 12:31:25.562+01" "2018-10-08 12:31:25.562+01"

From the code I would expect to see the following posts in the db Posts table:

    posts: [
      {
        name: 'post1',
        title: 'Croissants are tasty',
        text: 'I recently ate a croissant from France. It was nice.',
        category: 'croissants'
      },
      {
        name: 'post2',
        title: 'my fav techno music',
        text: 'I love the song TECHNO by TechnoGang.',
        category: 'techno'
      }
    ]

If I inspect the posts table in pgAdmin it's empty. No errors are reported.

Any ideas?

Sequelize v5 types problem

Hello,

I was following yours great tutorial but I tried to set up my project using Sequelize v5, instead of v4, however, I got many errors regarding types incompatibility. Please check my code below.

import * as Sequelize from 'sequelize';

export interface UserAttributes {
    id?: number;
    name: string;
    createdAt?: Date;
    updatedAt?: Date;
}

export interface UserInstance extends Sequelize.Instance<UserAttributes>, UserAttributes {}

Error: TS2694: Namespace "... /node_modules/sequelize/types/index" has no exported member "Instance"

Similar issue on StackOverflow:

I would be grateful if you could help me solve this problem.

Eager loading not working

Hello,

When trying to use eager loading like this:

app.get('/users', (req: Request, res: Response) => {
  db.User.findAll({
    include: [{
      model: db.Post
    }]
  })
    .then((users: UserInstance[]) => res.status(200).json({ users }))
    .catch(err => res.status(500).json({ err: ['oops', err] }));
});

by adding include, like shown in sequelize docs.

I got a SequelizeEagerLoadingError.

I do not know how to fix this for now.
Can someone replicate this ?
Thank you.

Adding Instance And ClassLevel Methods

Hi Sir thank you for your awesome tutorial on sequelize and typescript please can you let me know how can we add InstanceLevel and ClassLevelMethods in your code i am trying for a day now but could not acheive the desired results :-

const User = sequelize.define('user', { firstname: Sequelize.STRING });

// Adding a class level method
User.classLevelMethod = function() {
return 'foo';
};

// Adding an instance level method
User.prototype.instanceLevelMethod = function() {
return 'bar';
};
Thank You

Not able to run code

Generic type 'BelongsToCreateAssociationMixin<TAttributes, TInstance>' requires 2 type argument(s)

How to create custom field getter

Hi, How to create custom getter for fields?

import * as Sequelize from 'sequelize'

export interface EntryAttributes {
  id: number
  firstName: string
  lastName: string
  fullName: string
}

export type EntryInstance = Sequelize.Instance<EntryAttributes> &
  EntryAttributes

export default (
  sequelize: Sequelize.Sequelize,
  DataTypes: Sequelize.DataTypes
): Sequelize.Model<EntryInstance, EntryAttributes> => {
  const attributes: SequelizeAttributes<EntryAttributes> = {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: DataTypes.INTEGER(255)
    },
    firstName: {
      allowNull: false,
      type: DataTypes.STRING(255)
    },
    lastName: {
      allowNull: false,
      type: DataTypes.STRING(255)
    },
    fullName: {
      type: new DataTypes.VIRTUAL(DataTypes.STRING(255), ['firstName', 'lastName']),
      get () {
        // Error in this.get
        return `${this.get('firstName') ${this.get('lastName')}}`
      }
    }
  }
  const Entry = sequelize.define<EntryInstance, EntryAttributes>(
    'Entry',
    attributes
  )

  return Entry
}

I got this error:

error TS2339: Property 'get' does not exist on type 'String | DataTypeAbstract | DefineAttributeColumnOptions'.
  Property 'get' does not exist on type 'String'.

401         return `${this.get('firstName') ${this.get('lastName')}}`
                                         ~~~
Found 1 error.

How to create a typescript model with hook ?

hi Ahmerb, thank you for tutorial on sequelize and typescript, please can you let me know how we add hook in you code, I am trying but could not acheive the desired results.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.