watscho / express-mongodb-rest-api-boilerplate

A boilerplate for Node.js apps / Rest API / Authentication from scratch - express, mongodb (mongoose). Typescript
MIT License
618 stars 83 forks source link

How to get user? #17

Closed mylastore closed 4 years ago

mylastore commented 4 years ago

First of all thank you for sharing this awesome repo ;)

Sign-in endpoint returns token. How do I get the user data?

mylastore commented 4 years ago

Thank you

watscho commented 3 years ago

always welcome <3

export const ifetch = (url, { options = {}, accessToken = '' } = {}) =>
  fetch(url, {
    method: 'GET',
    ...options,
    headers: {
      'Content-Type': 'application/json',
      'Accept-Language': 'en',
      Authorization: `Bearer ${accessToken}`,
      ...options.headers
    }
  })

export const authService = {
  fetchUser: async ({ cookies }) => {
    const { accessToken } = cookies

    if (!accessToken)
      return {
        data: undefined,
        ok: true,
        status: 200
      }

    const url = process.env.API_AUTH_USER

    const response = await ifetch(url, { accessToken })

    const data = await response.json()

    return {
      data,
      ok: response.ok,
      status: response.status
    }
  }
}