'How can I get my User entity in UserApi to get connectin to db?
I have an apollo-express-server with redis cache. This is the index.ts:
const main = async () => {
const app = express();
app.use(
cors({
credentials: true,
origin: process.env.CLIENT_URL,
})
);
const router = express.Router();
const store = await createConnection();
const redis = new Redis({
port: Number(process.env.REDIS_PORT),
host: process.env.REDIS_HOST,
//password: process.env.REDIS_PASSWORD,
});
const RedisStore = connectRedis(session);
const redisStore = new RedisStore({
client: redis,
});
app.use(bodyParser.json());
app.use(
session({
store: redisStore,
name: process.env.COOKIE_NAME,
sameSite: "Strict",
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: false,
maxAge: 1000 * 60 * 60 * 24,
},
} as any)
);
app.use(router);
const dataSources = () => ({
// @ts-ignore
userAPI: new UserAPI({ store }),
});
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
dataSources,
context: ({ req, res }: any) => ({ req, res }),
});
await apolloServer.start();
apolloServer.applyMiddleware({ app, cors: false });
app.listen({ port: process.env.SERVER_PORT }, () => {
console.log(
`Server ready at http://localhost:${process.env.SERVER_PORT}${apolloServer.graphqlPath}`
);
});
};
main().catch((err) => {
console.error(err);
});
my UserApi class that contains implementations of a login method(for simplicity) is here:
export class UserAPI extends DataSource {
private readonly store: DataSource;
private context: any;
constructor(store: { store: DataSource }) {
super();
// @ts-ignore
this.store = store;
}
initialize(config: { context: any }) {
// @ts-ignore
this.context = config.context;
console.log("Context from initialize: ", config.context);
}
async login(email: string, password: string): Promise<UserResult> {
//this User throws an error DataSource is not set for this entity.
const user = await User.findOne({ where: { email } });
...
}
}
In previous versions of the apollo server I could use without the dataSource. Like this:
index.ts
...
const schema = makeExecutableSchema({ typeDefs, resolvers });
const apolloServer = new ApolloServer({
schema,
context: ({ req, res }: any) => ({ req, res }),
});
...
in resolvers I have defined the login function which uses another function from My custom UserRepo.
...
login: async (
obj: any,
args: { email: string; password: string },
ctx: GqlContext,
info: any
): Promise<string> => {
let user: UserResult;
// login is from UserRepo.ts
user = await login(args.email, args.password);
},
...
UserRepo.ts
...
export const login = async (
email: string,
password: string
): Promise<UserResult> => {
const user = await User.findOne({ where: { email } });
// some code ...
};
...
And everything is working. But with the new version of the apollo server I can't figure out how to do it. I am using
"apollo-server-express": "^3.6.4",
"express": "^4.17.3",
"express-session": "^1.17.2",
"graphql": "^15.8.0",
"graphql-middleware": "^6.1.18",
"graphql-subscriptions": "^2.0.0",
"graphql-tools": "^8.2.1",
"ioredis": "^4.28.5",
"pg": "^8.7.3",
"typeorm": "^0.3.1",
"typescript": "^4.6.2",
I can get my user from db in this way
const userRepository = getRepository(User);
let b = await userRepository.findOne({ where: { email } });
But then again if I want to change the user. Let's say I want to give e new date for loging in the save login function
user.lastModifiedOn = new Date("new date");
await user.save();
I get the same error.
Solution 1:[1]
Change "target"
in you tsconfig.json to "es6"
:
{
"compilerOptions": {
...
"target": "es6",
...
},
...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Zohnannor |