Created
November 5, 2015 00:28
-
-
Save moret/a83a56b3313dd13183ad to your computer and use it in GitHub Desktop.
Sequelize ordering by attributes with non-matching fieldnames
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'underscore'; | |
import Promise from 'bluebird'; | |
import { | |
GraphQLInt, | |
GraphQLList, | |
GraphQLObjectType, | |
GraphQLSchema, | |
GraphQLString | |
} from 'graphql'; | |
import { | |
resolver, | |
attributeFields, | |
defaultArgs, | |
defaultListArgs | |
} from 'graphql-sequelize'; | |
import Sequelize from 'sequelize'; | |
import express from 'express'; | |
import graphqlHTTP from 'express-graphql'; | |
import cors from 'cors'; | |
const peopleData = [ | |
{id: 1, name: 'John'}, | |
{id: 2, name: 'Jane'}, | |
{id: 3, name: 'Jill'} | |
]; | |
const sequelize = new Sequelize(process.env.DB); | |
const PersonModel = sequelize.define('Person', { | |
name: {type: Sequelize.STRING, field: 'fullName'} | |
}, { | |
tableName: 'LegacyPeople' | |
}); | |
const PersonType = new GraphQLObjectType({ | |
name: 'Person', | |
fields: () => (_.assign(attributeFields(PersonModel))) | |
}); | |
const travelType = new GraphQLObjectType({ | |
name: 'Travels', | |
fields: { | |
people: { | |
type: new GraphQLList(PersonType), | |
resolve: resolver(PersonModel), | |
args: _.assign(defaultListArgs(), { | |
name: {type: GraphQLString} | |
}) | |
} | |
} | |
}); | |
const rootSchema = new GraphQLSchema({ | |
query: new GraphQLObjectType({ | |
name: 'RootQueryType', | |
fields: { | |
travel: { | |
type: travelType, | |
resolve: () => (true) | |
} | |
} | |
}) | |
}); | |
const app = express(); | |
app.use(cors()); | |
app.use('/graphql', graphqlHTTP({ | |
schema: rootSchema, | |
pretty: true, | |
graphiql: true | |
})); | |
// exploded models drop and sync, and data insert for clarity | |
Promise.each( | |
[ | |
PersonModel | |
], | |
(Model) => Model.drop() | |
).then(() => ( | |
Promise.each( | |
[ | |
{Model: PersonModel, data: peopleData}, | |
], | |
(pair) => { | |
const {Model, data} = pair; | |
return Model.sync().then(() => ( | |
Promise.each(data, (entry) => ( | |
Model.create(entry) | |
)) | |
)); | |
} | |
) | |
)).then(() => { | |
const server = app.listen(process.env.PORT || 3000, () => { | |
console.log( | |
'Example app listening at http://%s:%s', | |
server.address().address, | |
server.address().port | |
); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment